diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index e6a4248..2d6cc49 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,23 +1,24 @@ --- -name: Hata Bildirimi (Bug Report) -about: FocusFlow'da karşılaştığınız bir hatayı bildirin +name: Bug Report +about: Report a defect in FocusFlow CLI or Desktop HUD title: '[BUG] ' labels: bug assignees: '' --- -**Hatanın Tanımı** -Hatanın ne olduğunu açık ve net bir şekilde açıklayın. +**Description** +A concise description of the issue encountered. -**Tekrarlama Adımları** -1. Şu ekranı açın '...' -2. Şuraya tıklayın '...' -3. Hatayı görün +**Steps to Reproduce** +1. Run command or open HUD tab '...' +2. Perform action '...' +3. Observe error '...' -**Beklenen Davranış** -Ne olması gerektiğini açıklayın. +**Expected Behavior** +Describe what should have happened instead. -**Sistem Bilgileri:** - - İşletim Sistemi: [Windows 10 / 11] - - Python Sürümü: [3.10+] - - FocusFlow Sürümü: [1.0.0] +**Environment** + - OS: [Windows 11 / Ubuntu 24.04 / macOS] + - Go Version: [1.23+] + - Python Version: [3.10+] + - FocusFlow Version: [2.1.0] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 18d5466..2563ea2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ name: CI on: push: - branches: [main] + branches: [main, 'feat/**'] pull_request: branches: [main] workflow_dispatch: @@ -12,8 +12,10 @@ permissions: jobs: test-go: - name: Go Test (${{ matrix.os }} - Go ${{ matrix.go-version }}) + name: Go (${{ matrix.os }} - Go ${{ matrix.go-version }}) runs-on: ${{ matrix.os }} + env: + CGO_ENABLED: '0' strategy: fail-fast: false matrix: @@ -33,24 +35,30 @@ jobs: - name: Go Vet run: go vet ./... - - name: Run Tests + - name: Go Test run: go test -v ./... - test-rust: - name: Rust Check & Test - runs-on: windows-latest - continue-on-error: true + test-python: + name: Python (${{ matrix.os }} - Python ${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python-version: ['3.11', '3.12', '3.13', '3.14'] + steps: - name: Checkout repository uses: actions/checkout@v4 - - name: Set up Rust - uses: dtolnay/rust-toolchain@stable + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true - - name: Cargo Check - run: cargo check --verbose - continue-on-error: true + - name: Install pytest + run: python -m pip install --upgrade pip pytest - - name: Cargo Test - run: cargo test --verbose - continue-on-error: true + - name: Run pytest suite + run: python -m pytest -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e158610..6b30867 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,8 +11,10 @@ permissions: jobs: build-and-release: - name: Build & Release FocusFlow + name: Verify, Build & Release FocusFlow runs-on: ubuntu-latest + env: + CGO_ENABLED: '0' steps: - name: Checkout repository uses: actions/checkout@v4 @@ -25,50 +27,83 @@ jobs: go-version: '1.24.x' check-latest: false + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: Verify Go vet & unit tests + run: | + go vet ./... + go test -v ./... + + - name: Verify Python pytest suite + run: | + python -m pip install --upgrade pip pytest + python -m pytest -v + - name: Install packaging tools run: sudo apt-get update && sudo apt-get install -y zip - name: Build cross-platform binaries run: | mkdir -p dist - + if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then + VERSION="${GITHUB_REF_NAME#v}" + else + VERSION="2.1.0" + fi + LDFLAGS="-s -w -X main.Version=${VERSION}" + # Windows amd64 - CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o dist/focusflow-windows-amd64.exe ./cmd/focusflow + GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-windows-amd64.exe ./cmd/focusflow (cd dist && zip focusflow-windows-amd64.zip focusflow-windows-amd64.exe) - + + # Windows arm64 + GOOS=windows GOARCH=arm64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-windows-arm64.exe ./cmd/focusflow + (cd dist && zip focusflow-windows-arm64.zip focusflow-windows-arm64.exe) + # Linux amd64 - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o dist/focusflow-linux-amd64 ./cmd/focusflow + GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-linux-amd64 ./cmd/focusflow tar -czvf dist/focusflow-linux-amd64.tar.gz -C dist focusflow-linux-amd64 - + # Linux arm64 - CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o dist/focusflow-linux-arm64 ./cmd/focusflow + GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-linux-arm64 ./cmd/focusflow tar -czvf dist/focusflow-linux-arm64.tar.gz -C dist focusflow-linux-arm64 - + # macOS amd64 - CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o dist/focusflow-darwin-amd64 ./cmd/focusflow + GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-darwin-amd64 ./cmd/focusflow tar -czvf dist/focusflow-darwin-amd64.tar.gz -C dist focusflow-darwin-amd64 - + # macOS arm64 - CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o dist/focusflow-darwin-arm64 ./cmd/focusflow + GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="${LDFLAGS}" -o dist/focusflow-darwin-arm64 ./cmd/focusflow tar -czvf dist/focusflow-darwin-arm64.tar.gz -C dist focusflow-darwin-arm64 - name: Generate SHA-256 Checksums run: | cd dist - sha256sum focusflow-windows-amd64.zip focusflow-linux-amd64.tar.gz focusflow-linux-arm64.tar.gz focusflow-darwin-amd64.tar.gz focusflow-darwin-arm64.tar.gz > checksums.txt + sha256sum \ + focusflow-windows-amd64.zip \ + focusflow-windows-arm64.zip \ + focusflow-linux-amd64.tar.gz \ + focusflow-linux-arm64.tar.gz \ + focusflow-darwin-amd64.tar.gz \ + focusflow-darwin-arm64.tar.gz > checksums.txt cat checksums.txt - name: Publish GitHub Release + if: startsWith(github.ref, 'refs/tags/v') uses: softprops/action-gh-release@v2 with: files: | dist/focusflow-windows-amd64.zip + dist/focusflow-windows-arm64.zip dist/focusflow-linux-amd64.tar.gz dist/focusflow-linux-arm64.tar.gz dist/focusflow-darwin-amd64.tar.gz dist/focusflow-darwin-arm64.tar.gz dist/checksums.txt - name: ${{ github.ref_name }} - Deep Work & Distraction Firewall CLI + name: ${{ github.ref_name }} - FocusFlow Deep Work & Distraction Shield generate_release_notes: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 4774533..674c784 100644 --- a/.gitignore +++ b/.gitignore @@ -207,7 +207,9 @@ marimo/_lsp/ __marimo__/ # Executables and builds +focusflow focusflow.exe +.focusflow/ target/ *.tmp *.bak diff --git a/CHANGELOG.md b/CHANGELOG.md index 86f889f..53f505d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,36 @@ # Changelog -FocusFlow projesine yapılan tüm önemli değişiklikler bu dosyada listelenir. +All notable changes to FocusFlow are documented in this file. + +## [2.1.0] - 2026-11-10 + +### Added +- Unified standard-library Python core package (`focusflow_core/`) shared with `FocusFlowGUI.py` and 100% interoperable with the Go CLI (`config.json`, `sessions.json`, `hosts.focusflow.journal.json`). +- Crash-safe write-ahead rollback journal (`hosts.focusflow.journal.json`) and automatic startup orphan recovery (`RecoverIfOrphaned`) across both Go CLI and Python HUD. +- Dual-stack IPv4 (`0.0.0.0`) + IPv6 (`::`) `hosts` sinkholing with expanded Anti-DoH endpoints (`dns.adguard-dns.com`, `dns.nextdns.io`, `doh.cleanbrowsing.org`, `doh.dns.sb`, `freedns.controld.com`) and mid-session tamper verification. +- Zero-dependency Python Win32 process supervisor using `ctypes` `CreateToolhelp32Snapshot` (`Process32FirstW`/`Process32NextW`) and `TerminateProcess`. +- Critical protected process and PID denylist across Go and Python (`csrss.exe`, `lsass.exe`, `svchost.exe`, `explorer.exe`, `python.exe`, `focusflow.exe`, `wt.exe`, etc.), plus `SystemInformer.exe` in hardcore `AntiCheatGuard`. +- New CLI commands and flags: `focusflow doctor`, `focusflow recover`, `focusflow export [--format json|csv] [--out ]`, `--elevate`, `stats --days`, and `--json` output on `status`, `list`, `stats`, `doctor`, and `recover`. +- Non-pasteable 16-character alphanumeric Friction Challenge in strict mode, `PER_MONITOR_AWARE_V2` High-DPI scaling, `[ELEVATE ADMIN]` UAC action, and JSON/CSV/PNG telemetry exports in the desktop HUD. +- Hermetic Go and Python (`pytest`) test suites and multi-OS CI matrix (`Go 1.23.x`/`1.24.x` and `Python 3.11`–`3.14`), plus `windows/arm64` release artifacts. + +### Changed +- Replaced drifted sleep countdowns with `time.monotonic()` phase deadlines and paused modal transitions so break timers never burn in the background while dialogs are open. +- Preserved Windows `hosts` DACLs via `ReplaceFileW` and POSIX permissions with `fsync` and 5x/40ms sharing-violation retries. +- Fixed Linux `/proc` process scanning so `ps` is never spawned on zero-match ticks and 15-byte `TASK_COMM_LEN` truncated names resolve via `/proc//exe` and `/proc//cmdline`. +- Purged seeded placeholder stats in favor of live telemetry computed from `sessions.json`. +- Standardized CLI and HUD on a strict zero-emoji Catppuccin Mocha systems aesthetic. + +### Removed +- Retired duplicate unmaintained Rust prototype (`Cargo.toml`, `src/`) and legacy V1 script (`legacy/FocusFlowV1.py`). + +## [2.0.0] - 2026-11-08 + +### Added +- Native Go CLI (`cmd/focusflow`, `pkg/engine`, `pkg/profile`, `pkg/storage`, `pkg/tui`) and Catppuccin Mocha Tkinter desktop GUI (`FocusFlowGUI.py`). +- Built-in `study`, `dev`, and `hardcore` focus profiles and cross-platform release workflow. ## [1.0.0] - 2026-11-05 -### Eklendi -- Pomodoro odaklanma zamanlayıcısı ve esnek modlar. -- Gelişmiş Win32 proses denetleyicisi ile dikkat dağıtıcı oyun ve uygulamaları otomatik sonlandırma. -- Anti-DoH korumalı DNS ve hosts engelleme motoru. -- Günlük ve haftalık çalışma istatistikleri ve grafik raporlama. -- GitHub Actions CI/CD otomatik derleme ve test entegrasyonu. +### Added +- Initial Pomodoro focus timer, process blocker, DNS/hosts blocking prototype, and weekly statistics view. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 33831df..87e5f26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,28 +1,38 @@ -# FocusFlow'a Katkıda Bulunma Rehberi +# Contributing to FocusFlow -FocusFlow açık kaynaklı bir topluluk projesidir. Hata bildirimleri, yeni özellik önerileri ve katkılarınızı memnuniyetle kabul ediyoruz! +FocusFlow is an open-source deep work systems utility built on a unified **Go CLI** + **zero-dependency Python Desktop HUD** architecture. Bug reports, security hardening improvements, and pull requests are welcome. -## Geliştirme Ortamı +## Development Prerequisites -### Gereksinimler -- **Python 3.10+** -- Git +- **Go 1.23+** (`CGO_ENABLED=0` standard-library build) +- **Python 3.10+** (standard library only at runtime; `pytest` for running tests) +- **Git** + +## Setup -### Kurulum ```bash git clone https://github.com/aloneangel45/FocusFlow.git cd FocusFlow -pip install -r requirements.txt +python -m pip install -e ".[dev]" ``` -### Testleri Çalıştırma +## Running the Hermetic Test Suites + +All tests isolate filesystem state via `FOCUSFLOW_HOME` and `FOCUSFLOW_HOSTS_PATH` temporary directories and must never modify real `%APPDATA%` or the host OS `hosts` file: + ```bash -pytest tests/ +# Go static analysis and unit tests +CGO_ENABLED=0 go vet ./... +CGO_ENABLED=0 go test -v ./... + +# Python unit and cross-runtime interop tests +python -m pytest -v ``` -### Katkı Süreci -1. Projeyi Fork'layın. -2. Yeni bir dal (branch) açın: `git checkout -b feat/yeni-ozellik` -3. Değişikliklerinizi yapın ve test edin. -4. Conventional Commits formatında commit atın (`feat:`, `fix:`, `docs:`). -5. Pull Request gönderin. +## Contribution Guidelines + +1. Fork the repository and create a topic branch (`git checkout -b feat/your-feature`). +2. Keep Go (`pkg/*`, `cmd/focusflow`) and Python (`focusflow_core/*`, `FocusFlowGUI.py`) schemas and behavior aligned whenever modifying state files (`config.json`, `sessions.json`, `hosts.focusflow.journal.json`) or `hosts` block markers. +3. Follow the zero-emoji minimal systems aesthetic across code, CLI tags, GUI labels, and documentation. +4. Ensure both `go test -v ./...` and `python -m pytest -v` pass cleanly. +5. Format commit messages according to Conventional Commits (`feat:`, `fix:`, `docs:`, `test:`, `ci:`, `chore:`) and open a Pull Request. diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 55bdb09..0000000 --- a/Cargo.lock +++ /dev/null @@ -1,893 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block2" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" -dependencies = [ - "objc2", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "cc" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "cfg_aliases" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "clap" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "clap_lex" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "colored" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" -dependencies = [ - "lazy_static", - "windows-sys 0.59.0", -] - -[[package]] -name = "console" -version = "0.15.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" -dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "unicode-width", - "windows-sys 0.59.0", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "ctrlc" -version = "3.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162" -dependencies = [ - "dispatch2", - "nix", - "windows-sys 0.61.2", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags", - "block2", - "libc", - "objc2", -] - -[[package]] -name = "encode_unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "focusflow" -version = "2.0.0" -dependencies = [ - "chrono", - "clap", - "colored", - "ctrlc", - "indicatif", - "serde", - "serde_json", - "sha2", - "tempfile", - "windows-sys 0.59.0", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "indicatif" -version = "0.17.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" -dependencies = [ - "console", - "number_prefix", - "portable-atomic", - "unicode-width", - "web-time", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "lazy_static" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "nix" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags", - "cfg-if", - "cfg_aliases", - "libc", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - -[[package]] -name = "objc2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" -dependencies = [ - "objc2-encode", -] - -[[package]] -name = "objc2-encode" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rustix" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-width" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.9", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 90890f0..0000000 --- a/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -[package] -name = "focusflow" -version = "2.0.0" -edition = "2021" -authors = ["aloneangel45 "] -description = "Kernel-level deep work discipline engine, atomic hosts blocker, and low-overhead process supervisor in Rust." -license = "MIT" -readme = "README.md" -repository = "https://github.com/aloneangel45/FocusFlow" -keywords = ["deepwork", "productivity", "hosts-blocker", "pomodoro", "rust"] -categories = ["command-line-utilities", "development-tools"] - -[dependencies] -clap = { version = "4.5", features = ["derive", "cargo"] } -windows-sys = { version = "0.59", features = [ - "Win32_System_Diagnostics_ToolHelp", - "Win32_System_Threading", - "Win32_Foundation", - "Win32_Security" -] } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -chrono = { version = "0.4", features = ["serde"] } -sha2 = "0.10" -colored = "2.1" -indicatif = "0.17" -tempfile = "3.10" -ctrlc = "3.4" - -[[bin]] -name = "focusflow" -path = "src/main.rs" - -[lib] -name = "focusflow" -path = "src/lib.rs" diff --git a/FocusFlowGUI.py b/FocusFlowGUI.py index b80872a..2990ec7 100644 --- a/FocusFlowGUI.py +++ b/FocusFlowGUI.py @@ -1,44 +1,81 @@ """ -FocusFlow V2 - Modern Desktop GUI -Engineered for High-Performance Deep Work & Distraction Shielding -Theme: Catppuccin Mocha Dark Modern Architecture -High-DPI Aware, Win32 Native Integration, Zero External Heavy Deps +FocusFlow v2.1.0 - Native Desktop Deep Work & Distraction Shield HUD +Theme: Catppuccin Mocha Minimal Systems Architecture (Zero-Emoji) +High-DPI Per-Monitor v2, Crash-Safe SHA-256 Hosts Engine, Win32 Toolhelp32 Supervisor """ -import sys -import os -import json -import time -import datetime -import threading -import subprocess +from __future__ import annotations + import ctypes +import datetime +import json +import os import random +import sys +import threading +import time import tkinter as tk -from tkinter import ttk, messagebox, simpledialog - -# High-DPI Scaling for Windows +from tkinter import filedialog, messagebox, simpledialog, ttk + +from focusflow_core import ( + DOH_BYPASS_DOMAINS, + AntiCheatGuard, + DomainValidationError, + HostsManager, + MonotonicPhaseTimer, + ProcessSupervisor, + ProcessValidationError, + SessionMeta, + SessionStore, + __version__, + elevate_self, + flush_dns_async, + generate_friction_token, + generate_session_id, + get_gui_settings_path, + get_state_dir, + is_elevated, + load_config, + load_or_default, + normalize_process_name, + sanitize_domain, + save_config, + shield_mode_label, +) + +# Optional Pillow support for visual PNG analytics card export try: - ctypes.windll.shcore.SetProcessDpiAwareness(1) -except Exception: - pass + from PIL import Image, ImageDraw -# PIL Support for Exporting Reports -try: - from PIL import Image, ImageDraw, ImageFont HAS_PIL = True except ImportError: HAS_PIL = False -# psutil check -try: - import psutil - HAS_PSUTIL = True -except ImportError: - HAS_PSUTIL = False -# Catppuccin Mocha Theme Palette -THEME = { +def configure_windows_dpi() -> None: + """Enable crisp Per-Monitor DPI Awareness v2 on Windows 10/11.""" + if sys.platform != "win32": + return + try: + # DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4 + ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) + return + except Exception: + pass + try: + # PROCESS_PER_MONITOR_DPI_AWARE = 2 + ctypes.windll.shcore.SetProcessDpiAwareness(2) + return + except Exception: + pass + try: + ctypes.windll.shcore.SetProcessDpiAwareness(1) + except Exception: + pass + + +# Catppuccin Mocha Palette +THEME: dict[str, str] = { "crust": "#11111b", "mantle": "#181825", "base": "#1e1e2e", @@ -58,990 +95,1795 @@ "teal": "#94e2d5", } -HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts" -REDIRECT_IP = "127.0.0.1" -APPDATA_DIR = os.path.join(os.environ.get("APPDATA", os.path.expanduser("~")), "FocusFlow") -CONFIG_PATH = os.path.join(APPDATA_DIR, "config.json") -SESSIONS_PATH = os.path.join(APPDATA_DIR, "sessions.json") -SETTINGS_FILE = os.path.join(APPDATA_DIR, "gui_settings.json") - -DEFAULT_QUOTES = [ - "Muhtaç olduğun kudret, damarlarındaki asil kanda mevcuttur! — Mustafa Kemal Atatürk", - "Başarı, disiplinin ve tavizsiz odaklanmanın eseridir.", - "Şu an rakibin çalışıyor; sen ne yapıyorsun?", - "Acı geçici, gurur ve zafer ise kalıcıdır.", - "Disiplin, gelip geçici motivasyonu her daim yener.", - "Her saniye paha biçilemez bir sermayedir; boşa harcama!", - "Büyük hedeflere ancak küçük bahaneleri terk edenler ulaşır.", - "Yarın deme; yarınlar asla bitmez. Bugün başla.", - "Başlamak için mükemmel olmak gerekmez, ama mükemmel olmak için başlamak şarttır.", - "Zirve asla kalabalık değildir; oraya sadece pes etmeyenler tırmanır.", - "Limitlerini zorla; sınır sadece zihnindedir.", - "En iyi intikam, ezici ve tartışmasız bir başarıdır.", - "Bir saatlik tavizsiz odak, bir ömürlük pişmanlığı önler.", - "Odaklanmak; en cazip dikkat dağıtıcılara tereddütsüz 'HAYIR' diyebilmektir.", - "Bugün döktüğün alın teri, yarın kazanacağın zaferin teminatıdır.", - "Zor, imkânsız demek değildir. Sadece daha fazla irade ister.", - "Gelecekteki sen, şu an yaptıkların için sana teşekkür edecek mi?", - "Durdurulamaz ol. Dünya pes edenlerle doludur." -] - -DEFAULT_SITES = [ - "youtube.com", "instagram.com", "twitter.com", "x.com", - "tiktok.com", "reddit.com", "twitch.tv", "netflix.com", - "facebook.com", "discord.com" -] - -DEFAULT_APPS = [ - "steam.exe", "discord.exe", "spotify.exe", "epicgameslauncher.exe", - "riotclientservices.exe", "telegram.exe", "battle.net.exe" +DEFAULT_QUOTES: list[str] = [ + "Discipline consistently outperforms fleeting motivation.", + "One hour of uncompromising deep work prevents a lifetime of regret.", + "Focus is the art of saying NO to every trivial distraction.", + "Muhtac oldugun kudret, damarlarindaki asil kanda mevcuttur. - M. Kemal Ataturk", + "Basari, disiplinin ve tavizsiz odaklanmanin eseridir.", + "Her saniye geri gelmeyen bir sermayedir; dikkatini koru.", + "Systems beat willpower when friction is engineered on your side.", + "Protect your attention as fiercely as your production infrastructure.", ] -def is_admin(): - try: - return ctypes.windll.shell32.IsUserAnAdmin() != 0 - except Exception: - return False - +class FrictionChallengeDialog(tk.Toplevel): + """High-friction non-pasteable 16-character alphanumeric unlock modal.""" + + def __init__(self, parent: tk.Misc, reason_label: str = "STRICT SESSION UNLOCK") -> None: + super().__init__(parent) + self.title("FocusFlow Friction Challenge") + self.configure(bg=THEME["base"]) + self.resizable(False, False) + self.transient(parent) + self.grab_set() + + self.passed = False + self.token = generate_friction_token(16) + + container = tk.Frame(self, bg=THEME["base"], padx=28, pady=24) + container.pack(fill="both", expand=True) + + tk.Label( + container, + text=f"[CHALLENGE] {reason_label}", + font=("Segoe UI Bold", 12), + fg=THEME["red"], + bg=THEME["base"], + ).pack(anchor="w") + + tk.Label( + container, + text="Clipboard paste is disabled. Type all 16 characters manually (case-insensitive, without spaces):", + font=("Segoe UI", 9), + fg=THEME["subtext"], + bg=THEME["base"], + wraplength=460, + justify="left", + ).pack(anchor="w", pady=(6, 14)) + + # Render challenge code onto a Canvas so text cannot be highlighted or copied + grouped = " - ".join(self.token[i : i + 4] for i in range(0, 16, 4)) + canvas = tk.Canvas(container, width=460, height=56, bg=THEME["crust"], highlightthickness=1, highlightbackground=THEME["surface1"]) + canvas.pack(fill="x", pady=(0, 14)) + canvas.create_text( + 230, + 28, + text=grouped, + fill=THEME["yellow"], + font=("Consolas", 16, "bold"), + ) + + self.entry = tk.Entry( + container, + bg=THEME["surface0"], + fg=THEME["text"], + insertbackground=THEME["text"], + font=("Consolas", 14), + relief="flat", + highlightthickness=1, + highlightbackground=THEME["surface2"], + ) + self.entry.pack(fill="x", ipady=7, pady=(0, 8)) + + # Block all paste bindings and middle/right-click paste shortcuts + for seq in ("", "", "", "<>", "", ""): + self.entry.bind(seq, lambda _e: "break") + self.entry.bind("", lambda _e: self._on_submit()) + self.entry.bind("", lambda _e: self._on_cancel()) + + self.lbl_error = tk.Label( + container, + text="", + font=("Segoe UI Semibold", 9), + fg=THEME["red"], + bg=THEME["base"], + ) + self.lbl_error.pack(anchor="w", pady=(0, 10)) + + btn_row = tk.Frame(container, bg=THEME["base"]) + btn_row.pack(fill="x") + + tk.Button( + btn_row, + text="[STAY FOCUSED]", + command=self._on_cancel, + font=("Segoe UI Bold", 10), + bg=THEME["green"], + fg=THEME["crust"], + relief="flat", + padx=16, + pady=7, + cursor="hand2", + ).pack(side="left") + + tk.Button( + btn_row, + text="[CONFIRM ABORT]", + command=self._on_submit, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["red"], + relief="flat", + padx=16, + pady=7, + cursor="hand2", + ).pack(side="right") + + self.protocol("WM_DELETE_WINDOW", self._on_cancel) + self.update_idletasks() + self.entry.focus_set() + + def _on_submit(self) -> None: + typed = self.entry.get().replace("-", "").replace(" ", "").strip().upper() + if typed == self.token: + self.passed = True + self.destroy() + return + # Regenerate fresh token on mismatch to defeat partial brute-force / scripts + self.lbl_error.config(text="[ERR] Challenge mismatch. Stay on task or enter exact characters.") + self.entry.delete(0, "end") -def flush_dns(): - try: - subprocess.run(["ipconfig", "/flushdns"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=0x08000000) - except Exception: - pass + def _on_cancel(self) -> None: + self.passed = False + self.destroy() class FocusFlowGUI: - def __init__(self, root): + def __init__(self, root: tk.Tk) -> None: self.root = root - self.root.title("FocusFlow v2.0 — Deep Work & Distraction Shield") - self.root.geometry("1020x760") - self.root.minsize(920, 680) + self.root.title(f"FocusFlow v{__version__} — Deep Work & Distraction Shield") + self.root.geometry("1060x780") + self.root.minsize(960, 700) self.root.configure(bg=THEME["base"]) - # State Variables + # Core engines & unified state directory + self.state_dir = get_state_dir() + os.makedirs(self.state_dir, exist_ok=True) + self.hosts_manager = HostsManager(state_dir=self.state_dir) + self.session_store = SessionStore(state_dir=self.state_dir) + + # Runtime state self.is_active = False - self.is_paused = False - self.remaining_seconds = 0 - self.total_session_seconds = 0 + self.hosts_engaged = False self.current_mode = "pomodoro" self.current_profile = "study" - self.pomo_state = "WORK" # WORK or BREAK + self.pomo_state = "WORK" self.pomo_cycle = 1 - self.blocked_attempts_count = 0 - self.emergency_code = "" - - # Ensure Directory - os.makedirs(APPDATA_DIR, exist_ok=True) - self.load_settings() - - # Styles & UI Setup + self.session_blocked_count = 0 + self.active_session_id = "" + self.active_session_start_utc: datetime.datetime | None = None + self.active_planned_minutes = 25 + self.phase_timer = MonotonicPhaseTimer() + self._supervisor_lock = threading.Lock() + self._proc_supervisor = ProcessSupervisor([]) + self._anticheat_guard = AntiCheatGuard("standard") + self._active_sinkhole_domains: list[str] = [] + self._active_session_meta: SessionMeta | None = None + + # Startup orphan crash/reboot recovery + self.startup_recovery = self.hosts_manager.recover_if_orphaned( + on_orphan_session=lambda sid: self.session_store.mark_orphaned_session(sid), + flush_async=True, + ) + + self.load_all_state() self.setup_styles() self.build_ui() + self.on_profile_change(initial=True) + self.refresh_analytics_ui() - # Start timer clock thread - self.timer_running = True - self.clock_thread = threading.Thread(target=self._clock_worker, daemon=True) + if self.startup_recovery.recovered: + self.lbl_status.config( + text=f"[RECOVERED] Restored clean hosts from prior interrupted session ({self.startup_recovery.reason})", + fg=THEME["yellow"], + ) + + self.worker_running = True + self.clock_thread = threading.Thread(target=self._clock_worker, name="FocusFlowClock", daemon=True) self.clock_thread.start() - # Process supervisor thread - self.supervisor_thread = threading.Thread(target=self._process_supervisor, daemon=True) + self.supervisor_thread = threading.Thread(target=self._supervisor_worker, name="FocusFlowSupervisor", daemon=True) self.supervisor_thread.start() self.root.protocol("WM_DELETE_WINDOW", self.on_close) - def load_settings(self): - self.settings = { - "sites": DEFAULT_SITES.copy(), - "apps": DEFAULT_APPS.copy(), + # ---------------- STATE & CONFIG SYNC ---------------- + def load_all_state(self) -> None: + self.config_store = load_config(state_dir=self.state_dir) + self.gui_prefs: dict[str, object] = { + "mode": "pomodoro", + "profile": "study", "pomo_work": 25, "pomo_break": 5, - "pomo_cycles": 4, "standard_duration": 60, + "flex_duration": 90, "strict_mode": True, - "streak": 3, - "last_date": datetime.date.today().strftime("%Y-%m-%d"), - "history": { - (datetime.date.today() - datetime.timedelta(days=i)).strftime("%Y-%m-%d"): random.randint(45, 180) - for i in range(6, -1, -1) - }, - "quotes": DEFAULT_QUOTES.copy() + "quotes": list(DEFAULT_QUOTES), } - if os.path.exists(SETTINGS_FILE): + prefs_path = get_gui_settings_path(self.state_dir) + if os.path.exists(prefs_path): try: - with open(SETTINGS_FILE, "r", encoding="utf-8") as f: + with open(prefs_path, "r", encoding="utf-8") as f: saved = json.load(f) - self.settings.update(saved) + if isinstance(saved, dict): + for key in ("mode", "profile", "pomo_work", "pomo_break", "standard_duration", "flex_duration", "strict_mode"): + if key in saved: + self.gui_prefs[key] = saved[key] + if isinstance(saved.get("quotes"), list) and saved["quotes"]: + self.gui_prefs["quotes"] = [str(q) for q in saved["quotes"] if str(q).strip()] except Exception: pass - # Also sync from Go engine config if exists - if os.path.exists(CONFIG_PATH): - try: - with open(CONFIG_PATH, "r", encoding="utf-8") as f: - go_cfg = json.load(f) - if "custom_sites" in go_cfg and go_cfg["custom_sites"]: - for s in go_cfg["custom_sites"]: - if s not in self.settings["sites"]: - self.settings["sites"].append(s) - if "custom_apps" in go_cfg and go_cfg["custom_apps"]: - for a in go_cfg["custom_apps"]: - if a not in self.settings["apps"]: - self.settings["apps"].append(a) - except Exception: - pass + self.current_mode = str(self.gui_prefs.get("mode", "pomodoro")) + if self.current_mode not in ("pomodoro", "standard", "flex"): + self.current_mode = "pomodoro" + self.current_profile = str(self.gui_prefs.get("profile", "study")) + if self.current_profile not in ("study", "dev", "hardcore"): + self.current_profile = "study" - def save_settings(self): + def save_gui_prefs(self) -> None: + prefs_path = get_gui_settings_path(self.state_dir) try: - with open(SETTINGS_FILE, "w", encoding="utf-8") as f: - json.dump(self.settings, f, indent=2, ensure_ascii=False) + with open(prefs_path, "w", encoding="utf-8") as f: + json.dump(self.gui_prefs, f, indent=2, ensure_ascii=False) except Exception: pass - def setup_styles(self): + def is_strict_active(self) -> bool: + if self.current_profile == "hardcore": + return True + return bool(self.gui_prefs.get("strict_mode", True)) + + def current_strictness_level(self) -> str: + if self.current_profile == "hardcore": + return "hardcore" + if bool(self.gui_prefs.get("strict_mode", True)): + return "standard" + return "relaxed" + + # ---------------- STYLES & MAIN LAYOUT ---------------- + def setup_styles(self) -> None: style = ttk.Style() style.theme_use("clam") - # Global Frame Styles style.configure("TFrame", background=THEME["base"]) style.configure("Card.TFrame", background=THEME["surface0"], relief="flat") style.configure("Surface.TFrame", background=THEME["mantle"], relief="flat") - # Notebook Tabs style.configure("TNotebook", background=THEME["base"], borderwidth=0) - style.configure("TNotebook.Tab", - background=THEME["mantle"], - foreground=THEME["subtext"], - padding=[20, 10], - font=("Segoe UI Semibold", 10), - borderwidth=0) - style.map("TNotebook.Tab", - background=[("selected", THEME["surface0"])], - foreground=[("selected", THEME["green"])]) - - # Treeview Styles - style.configure("Treeview", - background=THEME["surface0"], - foreground=THEME["text"], - fieldbackground=THEME["surface0"], - borderwidth=0, - font=("Segoe UI", 10), - rowheight=28) - style.configure("Treeview.Heading", - background=THEME["surface1"], - foreground=THEME["text"], - font=("Segoe UI Bold", 10), - relief="flat") - style.map("Treeview", - background=[("selected", THEME["blue"])], - foreground=[("selected", THEME["crust"])]) - - # Spinbox / Entry - style.configure("TSpinbox", - background=THEME["surface0"], - foreground=THEME["text"], - fieldbackground=THEME["surface0"], - arrowcolor=THEME["text"]) - style.configure("TEntry", - fieldbackground=THEME["surface0"], - foreground=THEME["text"], - insertcolor=THEME["text"]) - - def build_ui(self): - # 1. Top Navbar Header - header = tk.Frame(self.root, bg=THEME["mantle"], height=70) + style.configure( + "TNotebook.Tab", + background=THEME["mantle"], + foreground=THEME["subtext"], + padding=[18, 10], + font=("Segoe UI Semibold", 10), + borderwidth=0, + ) + style.map( + "TNotebook.Tab", + background=[("selected", THEME["surface0"])], + foreground=[("selected", THEME["green"])], + ) + + style.configure( + "Treeview", + background=THEME["surface0"], + foreground=THEME["text"], + fieldbackground=THEME["surface0"], + borderwidth=0, + font=("Segoe UI", 10), + rowheight=28, + ) + style.configure( + "Treeview.Heading", + background=THEME["surface1"], + foreground=THEME["text"], + font=("Segoe UI Bold", 10), + relief="flat", + ) + style.map( + "Treeview", + background=[("selected", THEME["blue"])], + foreground=[("selected", THEME["crust"])], + ) + + style.configure( + "TSpinbox", + background=THEME["surface0"], + foreground=THEME["text"], + fieldbackground=THEME["surface0"], + arrowcolor=THEME["text"], + ) + + def build_ui(self) -> None: + header = tk.Frame(self.root, bg=THEME["mantle"], height=68) header.pack(fill="x", side="top") header.pack_propagate(False) - # Brand Title & Logo title_box = tk.Frame(header, bg=THEME["mantle"]) - title_box.pack(side="left", padx=24, pady=12) + title_box.pack(side="left", padx=24, pady=14) + + tk.Label( + title_box, + text="FOCUSFLOW", + font=("Segoe UI Black", 18), + fg=THEME["green"], + bg=THEME["mantle"], + ).pack(side="left") + tk.Label( + title_box, + text=f" // v{__version__} NATIVE SHIELD", + font=("Consolas", 10, "bold"), + fg=THEME["subtext"], + bg=THEME["mantle"], + ).pack(side="left", pady=4) - tk.Label(title_box, text="⚡ FOCUSFLOW", font=("Segoe UI Black", 18), - fg=THEME["green"], bg=THEME["mantle"]).pack(side="left") - tk.Label(title_box, text=" v2.0 KERNEL SHIELD", font=("Segoe UI", 9, "bold"), - fg=THEME["subtext"], bg=THEME["mantle"]).pack(side="left", pady=4) - - # Status Badges on Right badge_box = tk.Frame(header, bg=THEME["mantle"]) - badge_box.pack(side="right", padx=24, pady=12) - - # Streak Badge - streak_count = self.settings.get("streak", 1) - streak_lbl = tk.Label(badge_box, text=f"🔥 {streak_count} GÜN SERİ", - font=("Segoe UI Bold", 10), - bg=THEME["surface0"], fg=THEME["peach"], - padx=12, pady=4) - streak_lbl.pack(side="right", padx=6) - - # Admin Badge - admin_state = "🛡️ YÖNETİCİ" if is_admin() else "⚠️ KISITLI (USER)" - admin_color = THEME["teal"] if is_admin() else THEME["yellow"] - admin_lbl = tk.Label(badge_box, text=admin_state, - font=("Segoe UI Bold", 10), - bg=THEME["surface0"], fg=admin_color, - padx=12, pady=4) - admin_lbl.pack(side="right", padx=6) - - # 2. Main Notebook Navigation Tabs + badge_box.pack(side="right", padx=24, pady=14) + + elevated = is_elevated() + if not elevated: + self.btn_elevate = tk.Button( + badge_box, + text="[ELEVATE ADMIN]", + command=self.action_elevate_admin, + font=("Segoe UI Bold", 9), + bg=THEME["peach"], + fg=THEME["crust"], + activebackground=THEME["yellow"], + activeforeground=THEME["crust"], + relief="flat", + padx=12, + pady=4, + cursor="hand2", + ) + self.btn_elevate.pack(side="right", padx=(6, 0)) + + shield_text = shield_mode_label(elevated) + shield_color = THEME["teal"] if elevated else THEME["yellow"] + self.lbl_shield_badge = tk.Label( + badge_box, + text=shield_text, + font=("Consolas", 9, "bold"), + bg=THEME["surface0"], + fg=shield_color, + padx=12, + pady=5, + ) + self.lbl_shield_badge.pack(side="right", padx=6) + + self.lbl_streak_badge = tk.Label( + badge_box, + text="STREAK: 0 DAYS", + font=("Consolas", 9, "bold"), + bg=THEME["surface0"], + fg=THEME["peach"], + padx=12, + pady=5, + ) + self.lbl_streak_badge.pack(side="right", padx=6) + self.notebook = ttk.Notebook(self.root) - self.notebook.pack(fill="both", expand=True, padx=20, pady=(15, 20)) + self.notebook.pack(fill="both", expand=True, padx=20, pady=(14, 18)) - # Tabs self.tab_timer = ttk.Frame(self.notebook) self.tab_blocks = ttk.Frame(self.notebook) self.tab_stats = ttk.Frame(self.notebook) self.tab_quotes = ttk.Frame(self.notebook) self.tab_settings = ttk.Frame(self.notebook) - self.notebook.add(self.tab_timer, text=" ⚡ ODAKLANMA ") - self.notebook.add(self.tab_blocks, text=" 🌐 ENGELLEME LİSTELERİ ") - self.notebook.add(self.tab_stats, text=" 📊 ANALİZ & GRAFİKLER ") - self.notebook.add(self.tab_quotes, text=" 💪 MOTİVASYON ") - self.notebook.add(self.tab_settings, text=" ⚙️ AYARLAR ") + self.notebook.add(self.tab_timer, text=" [01] FOCUS HUD ") + self.notebook.add(self.tab_blocks, text=" [02] BLOCKLISTS ") + self.notebook.add(self.tab_stats, text=" [03] ANALYTICS ") + self.notebook.add(self.tab_quotes, text=" [04] DISCIPLINE ") + self.notebook.add(self.tab_settings, text=" [05] SYSTEM ") - # Build individual tabs self.build_tab_timer() self.build_tab_blocks() self.build_tab_stats() self.build_tab_quotes() self.build_tab_settings() - # ---------------- TAB 1: TIMER & HUD ---------------- - def build_tab_timer(self): + self.notebook.bind("<>", self._on_tab_changed) + + def _on_tab_changed(self, _event: object) -> None: + selected = self.notebook.select() + if selected == str(self.tab_stats): + self.refresh_analytics_ui() + + # ---------------- TAB 1: FOCUS HUD ---------------- + def build_tab_timer(self) -> None: f = self.tab_timer - # Left Column: Big Timer & Control Center - left_card = tk.Frame(f, bg=THEME["surface0"], padx=30, pady=25) + left_card = tk.Frame(f, bg=THEME["surface0"], padx=30, pady=24) left_card.pack(side="left", fill="both", expand=True, padx=(0, 10), pady=10) - # Mode Indicator Pill - self.lbl_pomo_badge = tk.Label(left_card, text="POMODORO DERS", - font=("Segoe UI Bold", 11), - bg=THEME["surface1"], fg=THEME["green"], - padx=14, pady=4) + self.lbl_pomo_badge = tk.Label( + left_card, + text="POMODORO // STUDY", + font=("Consolas", 11, "bold"), + bg=THEME["surface1"], + fg=THEME["green"], + padx=14, + pady=4, + ) self.lbl_pomo_badge.pack(anchor="center", pady=(0, 10)) - # Giant Digital Clock - self.lbl_timer = tk.Label(left_card, text="25:00", - font=("Segoe UI", 68, "bold"), - fg=THEME["green"], bg=THEME["surface0"]) + self.lbl_timer = tk.Label( + left_card, + text="25:00", + font=("Consolas", 68, "bold"), + fg=THEME["green"], + bg=THEME["surface0"], + ) self.lbl_timer.pack(anchor="center", pady=10) - # Progress Canvas Bar - self.canvas_progress = tk.Canvas(left_card, height=12, bg=THEME["surface1"], - highlightthickness=0) - self.canvas_progress.pack(fill="x", padx=40, pady=(0, 20)) - self.draw_progress_bar(1.0) + self.canvas_progress = tk.Canvas( + left_card, + height=12, + bg=THEME["surface1"], + highlightthickness=0, + ) + self.canvas_progress.pack(fill="x", padx=36, pady=(0, 20)) + self.canvas_progress.bind("", lambda _e: self.draw_progress_bar(self._current_ratio())) + + self.lbl_status = tk.Label( + left_card, + text="[STANDBY] Ready to engage focus session", + font=("Segoe UI Semibold", 10), + fg=THEME["subtext"], + bg=THEME["surface0"], + ) + self.lbl_status.pack(anchor="center", pady=(0, 24)) - # Status text - self.lbl_status = tk.Label(left_card, text="● Sistem Hazır — Odaklanmaya Başla", - font=("Segoe UI Semibold", 11), - fg=THEME["subtext"], bg=THEME["surface0"]) - self.lbl_status.pack(anchor="center", pady=(0, 25)) - - # Primary Action Buttons btn_box = tk.Frame(left_card, bg=THEME["surface0"]) - btn_box.pack(anchor="center", pady=5) - - self.btn_toggle = tk.Button(btn_box, text="🔒 ODAKLANMAYI BAŞLAT", - command=self.toggle_session, - font=("Segoe UI Black", 12), - bg=THEME["green"], fg=THEME["crust"], - activebackground=THEME["teal"], activeforeground=THEME["crust"], - relief="flat", padx=24, pady=12, cursor="hand2") - self.btn_toggle.pack(side="left", padx=8) - - self.btn_break = tk.Button(btn_box, text="☕ MOLA VER", - command=self.give_break, - font=("Segoe UI Bold", 11), - bg=THEME["surface1"], fg=THEME["yellow"], - activebackground=THEME["surface2"], - relief="flat", padx=18, pady=12, state="disabled", cursor="hand2") - self.btn_break.pack(side="left", padx=8) - - self.btn_emergency = tk.Button(btn_box, text="🆘 ACİL KİLİT AÇ", - command=self.prompt_emergency, - font=("Segoe UI Bold", 11), - bg=THEME["surface1"], fg=THEME["red"], - activebackground=THEME["red"], activeforeground=THEME["crust"], - relief="flat", padx=16, pady=12, state="disabled", cursor="hand2") - self.btn_emergency.pack(side="left", padx=8) - - # Right Column: Profiles & Quick Setup - right_panel = tk.Frame(f, bg=THEME["base"], width=320) + btn_box.pack(anchor="center", pady=6) + + self.btn_toggle = tk.Button( + btn_box, + text="[START FOCUS]", + command=self.toggle_session, + font=("Segoe UI Black", 11), + bg=THEME["green"], + fg=THEME["crust"], + activebackground=THEME["teal"], + activeforeground=THEME["crust"], + relief="flat", + padx=22, + pady=11, + cursor="hand2", + ) + self.btn_toggle.pack(side="left", padx=6) + + self.btn_break = tk.Button( + btn_box, + text="[TAKE BREAK]", + command=self.give_break, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["yellow"], + activebackground=THEME["surface2"], + relief="flat", + padx=16, + pady=11, + state="disabled", + cursor="hand2", + ) + self.btn_break.pack(side="left", padx=6) + + self.btn_emergency = tk.Button( + btn_box, + text="[EMERGENCY UNLOCK]", + command=self.prompt_emergency, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["red"], + activebackground=THEME["red"], + activeforeground=THEME["crust"], + relief="flat", + padx=14, + pady=11, + state="disabled", + cursor="hand2", + ) + self.btn_emergency.pack(side="left", padx=6) + + # Right Column + right_panel = tk.Frame(f, bg=THEME["base"], width=330) right_panel.pack(side="right", fill="y", padx=(10, 0), pady=10) right_panel.pack_propagate(False) - # Mode Selection Card - mode_card = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=15) - mode_card.pack(fill="x", pady=(0, 15)) + mode_card = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=14) + mode_card.pack(fill="x", pady=(0, 12)) - tk.Label(mode_card, text="⚙️ ÇALIŞMA MODU", font=("Segoe UI Bold", 11), - fg=THEME["mauve"], bg=THEME["surface0"]).pack(anchor="w", pady=(0, 10)) + tk.Label( + mode_card, + text="SESSION MODE", + font=("Consolas", 10, "bold"), + fg=THEME["mauve"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 8)) self.mode_var = tk.StringVar(value=self.current_mode) - for val, label in [("pomodoro", "🍅 Pomodoro (25/5 dk)"), - ("standard", "⏱️ Sabit Süre"), - ("flex", "📅 Esnek Serbest Mod")]: - rb = tk.Radiobutton(mode_card, text=label, value=val, variable=self.mode_var, - command=self.on_mode_change, - font=("Segoe UI Semibold", 10), - fg=THEME["text"], bg=THEME["surface0"], - selectcolor=THEME["mantle"], activebackground=THEME["surface0"], - activeforeground=THEME["green"]) - rb.pack(anchor="w", pady=3) - - # Profile Selection Card - profile_card = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=15) - profile_card.pack(fill="x", pady=(0, 15)) - - tk.Label(profile_card, text="🛡️ PROFİL", font=("Segoe UI Bold", 11), - fg=THEME["sapphire"], bg=THEME["surface0"]).pack(anchor="w", pady=(0, 10)) + self.mode_radios: list[tk.Radiobutton] = [] + for val, label in ( + ("pomodoro", "Pomodoro Interval"), + ("standard", "Fixed Deep Work Block"), + ("flex", "Extended Open Sprint"), + ): + rb = tk.Radiobutton( + mode_card, + text=label, + value=val, + variable=self.mode_var, + command=self.on_mode_change, + font=("Segoe UI Semibold", 10), + fg=THEME["text"], + bg=THEME["surface0"], + selectcolor=THEME["mantle"], + activebackground=THEME["surface0"], + activeforeground=THEME["green"], + ) + rb.pack(anchor="w", pady=2) + self.mode_radios.append(rb) + + profile_card = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=14) + profile_card.pack(fill="x", pady=(0, 12)) + + tk.Label( + profile_card, + text="ACTIVE PROFILE", + font=("Consolas", 10, "bold"), + fg=THEME["sapphire"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 8)) self.profile_var = tk.StringVar(value=self.current_profile) - for p_val, p_lbl in [("study", "📚 Ders & Sınav (Tam Koruma)"), - ("dev", "💻 Geliştirici (Dev Mode)"), - ("hardcore", "🔥 Hardcore (Tavizsiz Kilit)")]: - rb = tk.Radiobutton(profile_card, text=p_lbl, value=p_val, variable=self.profile_var, - font=("Segoe UI Semibold", 10), - fg=THEME["text"], bg=THEME["surface0"], - selectcolor=THEME["mantle"], activebackground=THEME["surface0"], - activeforeground=THEME["sapphire"]) - rb.pack(anchor="w", pady=3) - - # Live Session Metrics Mini-Card - stats_mini = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=15) + self.profile_radios: list[tk.Radiobutton] = [] + for p_val, p_lbl in ( + ("study", "STUDY [25/5m - Full Academic]"), + ("dev", "DEV [50/10m - Docs Open]"), + ("hardcore", "AEGIS [Hardcore Anti-Cheat]"), + ): + rb = tk.Radiobutton( + profile_card, + text=p_lbl, + value=p_val, + variable=self.profile_var, + command=self.on_profile_change, + font=("Consolas", 9, "bold"), + fg=THEME["text"], + bg=THEME["surface0"], + selectcolor=THEME["mantle"], + activebackground=THEME["surface0"], + activeforeground=THEME["sapphire"], + ) + rb.pack(anchor="w", pady=2) + self.profile_radios.append(rb) + + stats_mini = tk.Frame(right_panel, bg=THEME["surface0"], padx=20, pady=14) stats_mini.pack(fill="x") - tk.Label(stats_mini, text="📈 ANLIK İSTATİSTİK", font=("Segoe UI Bold", 11), - fg=THEME["peach"], bg=THEME["surface0"]).pack(anchor="w", pady=(0, 10)) - - self.lbl_mini_blocked = tk.Label(stats_mini, text="Engellenen Girişim: 0", - font=("Segoe UI", 10), - fg=THEME["text"], bg=THEME["surface0"]) + tk.Label( + stats_mini, + text="LIVE TELEMETRY", + font=("Consolas", 10, "bold"), + fg=THEME["peach"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 8)) + + self.lbl_mini_profile_targets = tk.Label( + stats_mini, + text="Active Rules: 0 domains / 0 procs", + font=("Segoe UI", 9), + fg=THEME["subtext"], + bg=THEME["surface0"], + ) + self.lbl_mini_profile_targets.pack(anchor="w", pady=2) + + self.lbl_mini_blocked = tk.Label( + stats_mini, + text="Session Blocks: 0", + font=("Segoe UI Semibold", 10), + fg=THEME["text"], + bg=THEME["surface0"], + ) self.lbl_mini_blocked.pack(anchor="w", pady=2) - self.lbl_mini_cycles = tk.Label(stats_mini, text="Tamamlanan Döngü: 0", - font=("Segoe UI", 10), - fg=THEME["text"], bg=THEME["surface0"]) + self.lbl_mini_cycles = tk.Label( + stats_mini, + text="Completed Sprints: 0", + font=("Segoe UI Semibold", 10), + fg=THEME["text"], + bg=THEME["surface0"], + ) self.lbl_mini_cycles.pack(anchor="w", pady=2) - def draw_progress_bar(self, ratio): + def _current_ratio(self) -> float: + if self.is_active: + return self.phase_timer.progress_ratio() + return 1.0 + + def draw_progress_bar(self, ratio: float) -> None: self.canvas_progress.delete("all") w = self.canvas_progress.winfo_width() if w < 10: w = 500 h = 12 - ratio = max(0.0, min(1.0, ratio)) + clamped = max(0.0, min(1.0, ratio)) self.canvas_progress.create_rectangle(0, 0, w, h, fill=THEME["surface1"], width=0) fill_color = THEME["green"] if self.pomo_state == "WORK" else THEME["blue"] - self.canvas_progress.create_rectangle(0, 0, int(w * ratio), h, fill=fill_color, width=0) + self.canvas_progress.create_rectangle(0, 0, int(w * clamped), h, fill=fill_color, width=0) + + def on_profile_change(self, initial: bool = False) -> None: + if self.is_active: + self.profile_var.set(self.current_profile) + return + + selected = self.profile_var.get().strip().lower() + if selected not in ("study", "dev", "hardcore"): + selected = "study" + self.current_profile = selected + self.gui_prefs["profile"] = selected + + prof = load_or_default(selected, state_dir=self.state_dir) + self.active_profile_obj = prof + + if not initial: + self.gui_prefs["pomo_work"] = prof.default_work_minutes + self.gui_prefs["pomo_break"] = prof.default_break_minutes + if selected == "hardcore": + self.gui_prefs["strict_mode"] = True + if hasattr(self, "strict_var"): + self.strict_var.set(True) + if hasattr(self, "spin_p_work"): + self.spin_p_work.set(prof.default_work_minutes) + if hasattr(self, "spin_p_break"): + self.spin_p_break.set(prof.default_break_minutes) + self.save_gui_prefs() + + self.lbl_mini_profile_targets.config( + text=f"Active Rules: {len(prof.blocked_domains)} domains / {len(prof.blocked_processes)} procs" + ) + self.refresh_lists() + self.on_mode_change() - def on_mode_change(self): + def on_mode_change(self) -> None: if self.is_active: + self.mode_var.set(self.current_mode) return + m = self.mode_var.get() self.current_mode = m + self.gui_prefs["mode"] = m + self.save_gui_prefs() + + prof_tag = self.current_profile.upper() if m == "pomodoro": - self.lbl_timer.config(text=f"{self.settings.get('pomo_work', 25):02d}:00", fg=THEME["green"]) - self.lbl_pomo_badge.config(text="POMODORO DERS", fg=THEME["green"]) + mins = int(self.gui_prefs.get("pomo_work", 25)) + self.lbl_timer.config(text=f"{mins:02d}:00", fg=THEME["green"]) + self.lbl_pomo_badge.config(text=f"POMODORO // {prof_tag}", fg=THEME["green"]) elif m == "standard": - self.lbl_timer.config(text=f"{self.settings.get('standard_duration', 60):02d}:00", fg=THEME["sapphire"]) - self.lbl_pomo_badge.config(text="STANDART ÇALIŞMA", fg=THEME["sapphire"]) + mins = int(self.gui_prefs.get("standard_duration", 60)) + self.lbl_timer.config(text=f"{mins:02d}:00", fg=THEME["sapphire"]) + self.lbl_pomo_badge.config(text=f"DEEP WORK // {prof_tag}", fg=THEME["sapphire"]) else: - self.lbl_timer.config(text="SERBEST", fg=THEME["peach"]) - self.lbl_pomo_badge.config(text="ESNEK MOD", fg=THEME["peach"]) + mins = int(self.gui_prefs.get("flex_duration", 90)) + self.lbl_timer.config(text=f"{mins:02d}:00", fg=THEME["peach"]) + self.lbl_pomo_badge.config(text=f"EXTENDED // {prof_tag}", fg=THEME["peach"]) + self.draw_progress_bar(1.0) # ---------------- TAB 2: BLOCKLISTS ---------------- - def build_tab_blocks(self): + def build_tab_blocks(self) -> None: f = self.tab_blocks - # Paned layout: Sites on left, Apps on right - paned = tk.PanedWindow(f, orient="horizontal", bg=THEME["base"], sashwidth=6) + paned = tk.PanedWindow(f, orient="horizontal", bg=THEME["base"], sashwidth=8) paned.pack(fill="both", expand=True, padx=10, pady=10) - # Left Card: Websites + # Domains Card card_sites = tk.Frame(paned, bg=THEME["surface0"], padx=16, pady=16) - paned.add(card_sites, minsize=400) + paned.add(card_sites, minsize=420) - header_sites = tk.Frame(card_sites, bg=THEME["surface0"]) - header_sites.pack(fill="x", pady=(0, 10)) - tk.Label(header_sites, text="🌐 ENGELLENEN SİTELER", font=("Segoe UI Bold", 12), - fg=THEME["blue"], bg=THEME["surface0"]).pack(side="left") + tk.Label( + card_sites, + text="BLOCKED DOMAINS (DUAL-STACK IPv4 + IPv6)", + font=("Consolas", 10, "bold"), + fg=THEME["blue"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 10)) - # Entry & Add Button input_site_box = tk.Frame(card_sites, bg=THEME["surface0"]) input_site_box.pack(fill="x", pady=(0, 10)) - self.ent_site = tk.Entry(input_site_box, bg=THEME["mantle"], fg=THEME["text"], - font=("Segoe UI", 10), insertbackground=THEME["text"], - relief="flat", highlightthickness=1, highlightbackground=THEME["surface1"]) + self.ent_site = tk.Entry( + input_site_box, + bg=THEME["mantle"], + fg=THEME["text"], + font=("Consolas", 10), + insertbackground=THEME["text"], + relief="flat", + highlightthickness=1, + highlightbackground=THEME["surface1"], + ) self.ent_site.pack(side="left", fill="x", expand=True, ipady=6, padx=(0, 8)) - self.ent_site.bind("", lambda e: self.add_site()) - - btn_add_site = tk.Button(input_site_box, text="+ EKLE", command=self.add_site, - font=("Segoe UI Bold", 9), bg=THEME["blue"], fg=THEME["crust"], - relief="flat", padx=12, pady=5, cursor="hand2") - btn_add_site.pack(side="right") - - # Sites Treeview - self.tree_sites = ttk.Treeview(card_sites, columns=("domain",), show="headings", selectmode="browse") - self.tree_sites.heading("domain", text="Alan Adı (Domain)") - self.tree_sites.column("domain", anchor="w") + self.ent_site.bind("", lambda _e: self.add_site()) + + tk.Button( + input_site_box, + text="[+ ADD]", + command=self.add_site, + font=("Segoe UI Bold", 9), + bg=THEME["blue"], + fg=THEME["crust"], + relief="flat", + padx=12, + pady=5, + cursor="hand2", + ).pack(side="right") + + self.tree_sites = ttk.Treeview(card_sites, columns=("domain", "source"), show="headings", selectmode="browse") + self.tree_sites.heading("domain", text="Domain") + self.tree_sites.heading("source", text="Scope") + self.tree_sites.column("domain", anchor="w", width=260) + self.tree_sites.column("source", anchor="center", width=90) self.tree_sites.pack(fill="both", expand=True, pady=(0, 10)) - # Bottom buttons for sites sites_btn_bar = tk.Frame(card_sites, bg=THEME["surface0"]) sites_btn_bar.pack(fill="x") - tk.Button(sites_btn_bar, text="🗑️ Seçileni Sil", command=self.remove_site, - font=("Segoe UI", 9), bg=THEME["surface1"], fg=THEME["red"], - relief="flat", padx=10, pady=4, cursor="hand2").pack(side="left") - tk.Button(sites_btn_bar, text="🔄 Varsayılanları Yükle", command=self.reset_default_sites, - font=("Segoe UI", 9), bg=THEME["surface1"], fg=THEME["subtext"], - relief="flat", padx=10, pady=4, cursor="hand2").pack(side="right") - - # Right Card: Applications + tk.Button( + sites_btn_bar, + text="[REMOVE CUSTOM]", + command=self.remove_site, + font=("Segoe UI Semibold", 9), + bg=THEME["surface1"], + fg=THEME["red"], + relief="flat", + padx=10, + pady=4, + cursor="hand2", + ).pack(side="left") + tk.Button( + sites_btn_bar, + text="[CLEAR CUSTOM]", + command=self.reset_custom_sites, + font=("Segoe UI Semibold", 9), + bg=THEME["surface1"], + fg=THEME["subtext"], + relief="flat", + padx=10, + pady=4, + cursor="hand2", + ).pack(side="right") + + # Processes Card card_apps = tk.Frame(paned, bg=THEME["surface0"], padx=16, pady=16) - paned.add(card_apps, minsize=400) + paned.add(card_apps, minsize=420) - header_apps = tk.Frame(card_apps, bg=THEME["surface0"]) - header_apps.pack(fill="x", pady=(0, 10)) - tk.Label(header_apps, text="💻 ENGELLENEN UYGULAMALAR", font=("Segoe UI Bold", 12), - fg=THEME["mauve"], bg=THEME["surface0"]).pack(side="left") + tk.Label( + card_apps, + text="BLOCKED PROCESSES (WIN32 TOOLHELP32 GUARD)", + font=("Consolas", 10, "bold"), + fg=THEME["mauve"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 10)) input_app_box = tk.Frame(card_apps, bg=THEME["surface0"]) input_app_box.pack(fill="x", pady=(0, 10)) - self.ent_app = tk.Entry(input_app_box, bg=THEME["mantle"], fg=THEME["text"], - font=("Segoe UI", 10), insertbackground=THEME["text"], - relief="flat", highlightthickness=1, highlightbackground=THEME["surface1"]) + self.ent_app = tk.Entry( + input_app_box, + bg=THEME["mantle"], + fg=THEME["text"], + font=("Consolas", 10), + insertbackground=THEME["text"], + relief="flat", + highlightthickness=1, + highlightbackground=THEME["surface1"], + ) self.ent_app.pack(side="left", fill="x", expand=True, ipady=6, padx=(0, 8)) - self.ent_app.bind("", lambda e: self.add_app()) - - btn_add_app = tk.Button(input_app_box, text="+ EKLE", command=self.add_app, - font=("Segoe UI Bold", 9), bg=THEME["mauve"], fg=THEME["crust"], - relief="flat", padx=12, pady=5, cursor="hand2") - btn_add_app.pack(side="right") - - # Apps Treeview - self.tree_apps = ttk.Treeview(card_apps, columns=("app",), show="headings", selectmode="browse") - self.tree_apps.heading("app", text="İşlem Adı (Process)") - self.tree_apps.column("app", anchor="w") + self.ent_app.bind("", lambda _e: self.add_app()) + + tk.Button( + input_app_box, + text="[+ ADD]", + command=self.add_app, + font=("Segoe UI Bold", 9), + bg=THEME["mauve"], + fg=THEME["crust"], + relief="flat", + padx=12, + pady=5, + cursor="hand2", + ).pack(side="right") + + self.tree_apps = ttk.Treeview(card_apps, columns=("app", "source"), show="headings", selectmode="browse") + self.tree_apps.heading("app", text="Executable") + self.tree_apps.heading("source", text="Scope") + self.tree_apps.column("app", anchor="w", width=260) + self.tree_apps.column("source", anchor="center", width=90) self.tree_apps.pack(fill="both", expand=True, pady=(0, 10)) - # Bottom buttons for apps apps_btn_bar = tk.Frame(card_apps, bg=THEME["surface0"]) apps_btn_bar.pack(fill="x") - tk.Button(apps_btn_bar, text="🗑️ Seçileni Sil", command=self.remove_app, - font=("Segoe UI", 9), bg=THEME["surface1"], fg=THEME["red"], - relief="flat", padx=10, pady=4, cursor="hand2").pack(side="left") - tk.Button(apps_btn_bar, text="🔄 Varsayılanları Yükle", command=self.reset_default_apps, - font=("Segoe UI", 9), bg=THEME["surface1"], fg=THEME["subtext"], - relief="flat", padx=10, pady=4, cursor="hand2").pack(side="right") - - # Populate lists - self.refresh_lists() + tk.Button( + apps_btn_bar, + text="[REMOVE CUSTOM]", + command=self.remove_app, + font=("Segoe UI Semibold", 9), + bg=THEME["surface1"], + fg=THEME["red"], + relief="flat", + padx=10, + pady=4, + cursor="hand2", + ).pack(side="left") + tk.Button( + apps_btn_bar, + text="[CLEAR CUSTOM]", + command=self.reset_custom_apps, + font=("Segoe UI Semibold", 9), + bg=THEME["surface1"], + fg=THEME["subtext"], + relief="flat", + padx=10, + pady=4, + cursor="hand2", + ).pack(side="right") + + def refresh_lists(self) -> None: + self.config_store = load_config(state_dir=self.state_dir) + prof = self.config_store.profiles.get(self.current_profile) + prof_domains = set(prof.blocked_domains if prof else []) + custom_domains = set(self.config_store.custom_domains) - def refresh_lists(self): for item in self.tree_sites.get_children(): self.tree_sites.delete(item) - for s in sorted(self.settings.get("sites", [])): - self.tree_sites.insert("", "end", values=(s,)) + for d in sorted(prof_domains | custom_domains): + scope = "CUSTOM" if d in custom_domains else f"PROFILE:{self.current_profile.upper()}" + self.tree_sites.insert("", "end", values=(d, scope)) + prof_procs = set(prof.blocked_processes if prof else []) + custom_procs = set(self.config_store.custom_processes) for item in self.tree_apps.get_children(): self.tree_apps.delete(item) - for a in sorted(self.settings.get("apps", [])): - self.tree_apps.insert("", "end", values=(a,)) - - def add_site(self): - val = self.ent_site.get().strip().lower() - if not val: + for p in sorted(prof_procs | custom_procs): + scope = "CUSTOM" if p in custom_procs else f"PROFILE:{self.current_profile.upper()}" + self.tree_apps.insert("", "end", values=(p, scope)) + + merged = load_or_default(self.current_profile, state_dir=self.state_dir) + self.active_profile_obj = merged + self.lbl_mini_profile_targets.config( + text=f"Active Rules: {len(merged.blocked_domains)} domains / {len(merged.blocked_processes)} procs" + ) + + def add_site(self) -> None: + raw = self.ent_site.get() + if not raw.strip(): return - val = val.replace("https://", "").replace("http://", "").split("/")[0] - if val.startswith("www."): - val = val[4:] - if val not in self.settings["sites"]: - self.settings["sites"].append(val) - self.save_settings() - self.refresh_lists() - self.ent_site.delete(0, "end") + try: + clean = sanitize_domain(raw) + except DomainValidationError as exc: + messagebox.showerror("Invalid Domain", f"Rejected domain input:\n{exc}") + return + + cfg = load_config(state_dir=self.state_dir) + if clean not in cfg.custom_domains: + cfg.custom_domains.append(clean) + save_config(cfg, state_dir=self.state_dir) + self.ent_site.delete(0, "end") + self.refresh_lists() - def remove_site(self): + def remove_site(self) -> None: + if self.is_active and self.is_strict_active(): + messagebox.showwarning("Shield Locked", "Cannot remove blocked domains during an active strict sprint.") + return sel = self.tree_sites.selection() if not sel: return - val = self.tree_sites.item(sel[0], "values")[0] - if val in self.settings["sites"]: - self.settings["sites"].remove(val) - self.save_settings() + val, scope = self.tree_sites.item(sel[0], "values") + if scope != "CUSTOM": + messagebox.showinfo("Profile Rule", f"'{val}' belongs to built-in profile '{self.current_profile}'. Switch profiles to change preset rules.") + return + cfg = load_config(state_dir=self.state_dir) + if val in cfg.custom_domains: + cfg.custom_domains.remove(val) + save_config(cfg, state_dir=self.state_dir) self.refresh_lists() - def reset_default_sites(self): - self.settings["sites"] = DEFAULT_SITES.copy() - self.save_settings() + def reset_custom_sites(self) -> None: + if self.is_active and self.is_strict_active(): + messagebox.showwarning("Shield Locked", "Cannot clear custom domains during an active strict sprint.") + return + cfg = load_config(state_dir=self.state_dir) + cfg.custom_domains = [] + save_config(cfg, state_dir=self.state_dir) self.refresh_lists() - def add_app(self): - val = self.ent_app.get().strip().lower() - if not val: + def add_app(self) -> None: + raw = self.ent_app.get() + if not raw.strip(): + return + try: + clean_proc = normalize_process_name(raw) + except ProcessValidationError as exc: + messagebox.showerror("Protected or Invalid Process", f"Cannot add process:\n{exc}") return - if not val.endswith(".exe"): - val += ".exe" - if val not in self.settings["apps"]: - self.settings["apps"].append(val) - self.save_settings() - self.refresh_lists() - self.ent_app.delete(0, "end") - def remove_app(self): + cfg = load_config(state_dir=self.state_dir) + if clean_proc not in cfg.custom_processes: + cfg.custom_processes.append(clean_proc) + save_config(cfg, state_dir=self.state_dir) + self.ent_app.delete(0, "end") + self.refresh_lists() + + def remove_app(self) -> None: + if self.is_active and self.is_strict_active(): + messagebox.showwarning("Shield Locked", "Cannot remove blocked processes during an active strict sprint.") + return sel = self.tree_apps.selection() if not sel: return - val = self.tree_apps.item(sel[0], "values")[0] - if val in self.settings["apps"]: - self.settings["apps"].remove(val) - self.save_settings() + val, scope = self.tree_apps.item(sel[0], "values") + if scope != "CUSTOM": + messagebox.showinfo("Profile Rule", f"'{val}' belongs to built-in profile '{self.current_profile}'.") + return + cfg = load_config(state_dir=self.state_dir) + if val in cfg.custom_processes: + cfg.custom_processes.remove(val) + save_config(cfg, state_dir=self.state_dir) self.refresh_lists() - def reset_default_apps(self): - self.settings["apps"] = DEFAULT_APPS.copy() - self.save_settings() + def reset_custom_apps(self) -> None: + if self.is_active and self.is_strict_active(): + messagebox.showwarning("Shield Locked", "Cannot clear custom processes during an active strict sprint.") + return + cfg = load_config(state_dir=self.state_dir) + cfg.custom_processes = [] + save_config(cfg, state_dir=self.state_dir) self.refresh_lists() - # ---------------- TAB 3: STATS & CHARTS ---------------- - def build_tab_stats(self): + # ---------------- TAB 3: ANALYTICS & EXPORTS ---------------- + def build_tab_stats(self) -> None: f = self.tab_stats - # Top KPI Cards top_kpis = tk.Frame(f, bg=THEME["base"]) top_kpis.pack(fill="x", pady=10) - history = self.settings.get("history", {}) - total_mins = sum(history.values()) - streak = self.settings.get("streak", 1) - - for col, (title, val, color) in enumerate([ - ("TOPLAM ODAK", f"{total_mins} Dk", THEME["green"]), - ("AKTİF SERİ", f"{streak} Gün", THEME["peach"]), - ("ENGELLENENLER", f"{self.blocked_attempts_count} Adet", THEME["red"]), - ("HAFTALIK ORT.", f"{total_mins // max(1, len(history))} Dk/Gün", THEME["sapphire"]) - ]): - kpi_card = tk.Frame(top_kpis, bg=THEME["surface0"], padx=20, pady=14) - kpi_card.pack(side="left", fill="x", expand=True, padx=6) - tk.Label(kpi_card, text=title, font=("Segoe UI Bold", 9), - fg=THEME["subtext"], bg=THEME["surface0"]).pack(anchor="w") - tk.Label(kpi_card, text=val, font=("Segoe UI Black", 18), - fg=color, bg=THEME["surface0"]).pack(anchor="w", pady=(4, 0)) - - # Big Weekly Chart Canvas - chart_card = tk.Frame(f, bg=THEME["surface0"], padx=20, pady=20) - chart_card.pack(fill="both", expand=True, pady=10) - - tk.Label(chart_card, text="📊 SON 7 GÜNLÜK ÇALIŞMA PERFORMANSI (DAKİKA)", - font=("Segoe UI Bold", 11), fg=THEME["text"], bg=THEME["surface0"]).pack(anchor="w", pady=(0, 15)) + self.kpi_labels: dict[str, tk.Label] = {} + for key, title, color in ( + ("hours", "DEEP WORK TOTAL", THEME["green"]), + ("streak", "ACTIVE STREAK", THEME["peach"]), + ("rate", "COMPLETION RATE", THEME["sapphire"]), + ("blocked", "DISTRACTIONS KILLED", THEME["red"]), + ): + kpi_card = tk.Frame(top_kpis, bg=THEME["surface0"], padx=18, pady=14) + kpi_card.pack(side="left", fill="x", expand=True, padx=5) + tk.Label( + kpi_card, + text=title, + font=("Consolas", 9, "bold"), + fg=THEME["subtext"], + bg=THEME["surface0"], + ).pack(anchor="w") + val_lbl = tk.Label( + kpi_card, + text="0", + font=("Segoe UI Black", 17), + fg=color, + bg=THEME["surface0"], + ) + val_lbl.pack(anchor="w", pady=(4, 0)) + self.kpi_labels[key] = val_lbl + + chart_card = tk.Frame(f, bg=THEME["surface0"], padx=20, pady=18) + chart_card.pack(fill="both", expand=True, pady=8) + + tk.Label( + chart_card, + text="LAST 7 DAYS FOCUS PERFORMANCE (MINUTES)", + font=("Consolas", 10, "bold"), + fg=THEME["text"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 12)) self.chart_canvas = tk.Canvas(chart_card, bg=THEME["mantle"], highlightthickness=0) self.chart_canvas.pack(fill="both", expand=True) - self.chart_canvas.bind("", lambda e: self.draw_stats_chart()) + self.chart_canvas.bind("", lambda _e: self.draw_stats_chart()) - # Bottom Bar: Export PNG Report btn_bar = tk.Frame(f, bg=THEME["base"]) - btn_bar.pack(fill="x", pady=10) - - tk.Button(btn_bar, text="📸 Grafik ve Raporu PNG Olarak İndir", - command=self.export_report_png, - font=("Segoe UI Bold", 10), bg=THEME["surface0"], fg=THEME["green"], - relief="flat", padx=16, pady=8, cursor="hand2").pack(side="right") - - def draw_stats_chart(self): + btn_bar.pack(fill="x", pady=8) + + tk.Button( + btn_bar, + text="[EXPORT PNG]", + command=self.export_report_png, + font=("Segoe UI Bold", 9), + bg=THEME["surface0"], + fg=THEME["green"], + relief="flat", + padx=14, + pady=7, + cursor="hand2", + ).pack(side="right", padx=(6, 0)) + + tk.Button( + btn_bar, + text="[EXPORT CSV]", + command=lambda: self.export_telemetry_dialog("csv"), + font=("Segoe UI Bold", 9), + bg=THEME["surface0"], + fg=THEME["sapphire"], + relief="flat", + padx=14, + pady=7, + cursor="hand2", + ).pack(side="right", padx=6) + + tk.Button( + btn_bar, + text="[EXPORT JSON]", + command=lambda: self.export_telemetry_dialog("json"), + font=("Segoe UI Bold", 9), + bg=THEME["surface0"], + fg=THEME["mauve"], + relief="flat", + padx=14, + pady=7, + cursor="hand2", + ).pack(side="right", padx=6) + + def refresh_analytics_ui(self) -> None: + summary = self.session_store.compute_analytics(days=7) + self._latest_summary = summary + + streak_unit = "DAY" if summary.active_streak_days == 1 else "DAYS" + self.lbl_streak_badge.config(text=f"STREAK: {summary.active_streak_days} {streak_unit}") + self.lbl_mini_cycles.config(text=f"Completed Sprints: {summary.completed_sprints}") + + if hasattr(self, "kpi_labels"): + self.kpi_labels["hours"].config(text=f"{summary.total_hours:.1f}h ({summary.total_minutes}m)") + self.kpi_labels["streak"].config(text=f"{summary.active_streak_days} Days") + self.kpi_labels["rate"].config( + text=f"{summary.completion_rate:.0f}% ({summary.completed_sprints}/{summary.attempted_sprints})" + ) + self.kpi_labels["blocked"].config(text=str(summary.total_blocked + self.session_blocked_count)) + + if hasattr(self, "chart_canvas"): + self.draw_stats_chart() + + def draw_stats_chart(self) -> None: self.chart_canvas.delete("all") w = self.chart_canvas.winfo_width() h = self.chart_canvas.winfo_height() - if w < 100 or h < 100: + if w < 120 or h < 120: return - history = self.settings.get("history", {}) - dates = sorted(list(history.keys()))[-7:] - values = [history.get(d, 0) for d in dates] + summary = getattr(self, "_latest_summary", None) or self.session_store.compute_analytics(days=7) + daily = summary.daily + values = [d.minutes for d in daily] if not values or max(values) == 0: - self.chart_canvas.create_text(w // 2, h // 2, text="Henüz çalışma kaydı bulunmuyor", - fill=THEME["subtext"], font=("Segoe UI", 12)) + self.chart_canvas.create_text( + w // 2, + h // 2, + text="No completed focus sessions recorded yet. Start a sprint to populate telemetry.", + fill=THEME["subtext"], + font=("Segoe UI", 11), + ) return max_val = max(values) - padding_x = 60 - base_y = h - 50 - chart_h = h - 100 - bar_count = len(dates) + padding_x = 64 + base_y = h - 46 + chart_h = h - 96 + bar_count = len(daily) avail_w = w - (2 * padding_x) - bar_slot = avail_w / bar_count - bar_w = min(48, int(bar_slot * 0.55)) + bar_slot = avail_w / max(1, bar_count) + bar_w = min(52, int(bar_slot * 0.56)) - # Horizontal Gridlines - for level in [0.25, 0.5, 0.75, 1.0]: + for level in (0.25, 0.5, 0.75, 1.0): gy = base_y - (chart_h * level) - self.chart_canvas.create_line(padding_x, gy, w - padding_x, gy, fill=THEME["surface0"], width=1, dash=(3, 3)) - self.chart_canvas.create_text(padding_x - 12, gy, text=f"{int(max_val * level)}m", - fill=THEME["subtext"], font=("Segoe UI", 8), anchor="e") - - # Draw Bars - for i, (d_str, val) in enumerate(zip(dates, values)): - slot_center = padding_x + (i * bar_slot) + (bar_slot / 2) + self.chart_canvas.create_line( + padding_x, + gy, + w - padding_x, + gy, + fill=THEME["surface0"], + width=1, + dash=(3, 3), + ) + self.chart_canvas.create_text( + padding_x - 12, + gy, + text=f"{int(round(max_val * level))}m", + fill=THEME["subtext"], + font=("Consolas", 8), + anchor="e", + ) + + for idx, item in enumerate(daily): + slot_center = padding_x + (idx * bar_slot) + (bar_slot / 2) x0 = slot_center - (bar_w / 2) x1 = slot_center + (bar_w / 2) - bar_height = (val / max_val) * chart_h + bar_height = (item.minutes / max_val) * chart_h if max_val > 0 else 0 y0 = base_y - bar_height y1 = base_y - color = THEME["green"] if val >= 60 else THEME["sapphire"] - self.chart_canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="") - - # Top value label - self.chart_canvas.create_text(slot_center, y0 - 10, text=f"{val}", - fill=THEME["text"], font=("Segoe UI Bold", 9)) - - # Bottom date label - try: - short_date = datetime.datetime.strptime(d_str, "%Y-%m-%d").strftime("%d %b") - except Exception: - short_date = d_str - self.chart_canvas.create_text(slot_center, y1 + 18, text=short_date, - fill=THEME["subtext"], font=("Segoe UI", 8)) + color = THEME["green"] if item.minutes >= 50 else THEME["sapphire"] + if item.minutes > 0: + self.chart_canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="") + self.chart_canvas.create_text( + slot_center, + y0 - 11, + text=f"{item.minutes}m", + fill=THEME["text"], + font=("Consolas", 9, "bold"), + ) + short_date = item.date[-5:] + self.chart_canvas.create_text( + slot_center, + y1 + 18, + text=short_date, + fill=THEME["subtext"], + font=("Consolas", 8), + ) + + def export_telemetry_dialog(self, fmt: str) -> None: + ext = f".{fmt}" + default_name = f"focusflow_sessions_{datetime.date.today().strftime('%Y%m%d')}{ext}" + out_path = filedialog.asksaveasfilename( + parent=self.root, + title=f"Export FocusFlow {fmt.upper()} Report", + initialdir=self.state_dir, + initialfile=default_name, + defaultextension=ext, + filetypes=[(f"{fmt.upper()} files", f"*{ext}"), ("All files", "*.*")], + ) + if not out_path: + return + try: + saved = self.session_store.export_to_file(out_path, fmt=fmt, days=7) + messagebox.showinfo("Export Complete", f"Saved {fmt.upper()} telemetry report to:\n{saved}") + except Exception as exc: + messagebox.showerror("Export Failed", f"Could not export report:\n{exc}") - def export_report_png(self): + def export_report_png(self) -> None: if not HAS_PIL: - messagebox.showinfo("Bilgi", "PNG Çıktısı için Pillow kütüphanesi gerekiyor.") + messagebox.showinfo( + "Optional Dependency Missing", + "Visual PNG export requires the optional 'Pillow' package (pip install Pillow).\n" + "Use [EXPORT JSON] or [EXPORT CSV] for zero-dependency exports.", + ) + return + + default_name = f"FocusFlow_Report_{datetime.date.today().strftime('%Y%m%d')}.png" + export_path = filedialog.asksaveasfilename( + parent=self.root, + title="Export FocusFlow PNG Report", + initialdir=self.state_dir, + initialfile=default_name, + defaultextension=".png", + filetypes=[("PNG Image", "*.png")], + ) + if not export_path: return - export_path = os.path.join(APPDATA_DIR, f"FocusFlow_Report_{datetime.date.today().strftime('%Y%m%d')}.png") try: - img = Image.new("RGB", (900, 500), color="#1e1e2e") + summary = self.session_store.compute_analytics(days=7) + img = Image.new("RGB", (920, 520), color="#1e1e2e") draw = ImageDraw.Draw(img) - # Header - draw.rectangle([(0, 0), (900, 70)], fill="#181825") - draw.text((40, 20), "FOCUSFLOW ODALANMA PERFORMANS RAPORU", fill="#a6e3a1") - - history = self.settings.get("history", {}) - total_mins = sum(history.values()) - draw.text((40, 90), f"Toplam Odaklanma: {total_mins} Dakika | Seri: {self.settings.get('streak', 1)} Gün", fill="#cdd6f4") + draw.rectangle([(0, 0), (920, 72)], fill="#181825") + draw.text((36, 24), f"FOCUSFLOW v{__version__} // DEEP WORK TELEMETRY REPORT", fill="#a6e3a1") + draw.text( + (36, 94), + f"Total Focus: {summary.total_hours:.1f} hrs ({summary.total_minutes} min) | " + f"Streak: {summary.active_streak_days} days | " + f"Completion: {summary.completion_rate:.1f}% ({summary.completed_sprints}/{summary.attempted_sprints})", + fill="#cdd6f4", + ) + + max_val = max([d.minutes for d in summary.daily] + [1]) + base_y = 450 + chart_h = 280 + for idx, d in enumerate(summary.daily): + x0 = 60 + idx * 115 + x1 = x0 + 68 + bh = int((d.minutes / max_val) * chart_h) + y0 = base_y - bh + draw.rectangle([(x0, base_y - chart_h), (x1, base_y)], fill="#313244") + if bh > 0: + draw.rectangle([(x0, y0), (x1, base_y)], fill="#a6e3a1") + draw.text((x0 + 10, base_y + 12), d.date[-5:], fill="#a6adc8") + draw.text((x0 + 12, max(130, y0 - 18)), f"{d.minutes}m", fill="#cdd6f4") - # Save img.save(export_path) - messagebox.showinfo("Başarılı", f"Rapor kaydedildi:\n{export_path}") - except Exception as e: - messagebox.showerror("Hata", f"Rapor kaydedilemedi: {e}") + messagebox.showinfo("Export Complete", f"PNG report saved:\n{export_path}") + except Exception as exc: + messagebox.showerror("Export Failed", f"Could not save PNG report:\n{exc}") - # ---------------- TAB 4: MOTIVATION ---------------- - def build_tab_quotes(self): + # ---------------- TAB 4: DISCIPLINE QUOTES ---------------- + def build_tab_quotes(self) -> None: f = self.tab_quotes card = tk.Frame(f, bg=THEME["surface0"], padx=30, pady=30) card.pack(fill="both", expand=True, padx=20, pady=20) - tk.Label(card, text="💪 GÜNÜN MOTİVASYON VE DİSİPLİN İLKESİ", - font=("Segoe UI Bold", 13), fg=THEME["peach"], bg=THEME["surface0"]).pack(anchor="w") - - # Large Quote Box - self.quote_box = tk.Label(card, text=f'"{random.choice(self.settings["quotes"])}"', - font=("Segoe UI", 16, "italic"), - fg=THEME["text"], bg=THEME["mantle"], - wraplength=760, justify="center", padx=30, pady=40) - self.quote_box.pack(fill="x", pady=25) + tk.Label( + card, + text="DISCIPLINE MAXIMS", + font=("Consolas", 11, "bold"), + fg=THEME["peach"], + bg=THEME["surface0"], + ).pack(anchor="w") + + quotes = list(self.gui_prefs.get("quotes") or DEFAULT_QUOTES) + self.quote_box = tk.Label( + card, + text=f'"{random.choice(quotes)}"', + font=("Segoe UI", 15, "italic"), + fg=THEME["text"], + bg=THEME["mantle"], + wraplength=780, + justify="center", + padx=30, + pady=40, + ) + self.quote_box.pack(fill="x", pady=24) btn_box = tk.Frame(card, bg=THEME["surface0"]) btn_box.pack(anchor="w") - tk.Button(btn_box, text="🎲 Başka Söz Getir", command=self.next_quote, - font=("Segoe UI Bold", 10), bg=THEME["surface1"], fg=THEME["text"], - relief="flat", padx=16, pady=8, cursor="hand2").pack(side="left", padx=(0, 10)) - - tk.Button(btn_box, text="+ Kendi Sözünü Ekle", command=self.add_custom_quote, - font=("Segoe UI Bold", 10), bg=THEME["surface1"], fg=THEME["mauve"], - relief="flat", padx=16, pady=8, cursor="hand2").pack(side="left") - - def next_quote(self): - quotes = self.settings.get("quotes", DEFAULT_QUOTES) + tk.Button( + btn_box, + text="[NEXT MAXIM]", + command=self.next_quote, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["text"], + relief="flat", + padx=16, + pady=8, + cursor="hand2", + ).pack(side="left", padx=(0, 10)) + + tk.Button( + btn_box, + text="[+ ADD CUSTOM]", + command=self.add_custom_quote, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["mauve"], + relief="flat", + padx=16, + pady=8, + cursor="hand2", + ).pack(side="left") + + def next_quote(self) -> None: + quotes = list(self.gui_prefs.get("quotes") or DEFAULT_QUOTES) self.quote_box.config(text=f'"{random.choice(quotes)}"') - def add_custom_quote(self): - new_q = simpledialog.askstring("Yeni Söz Ekle", "Motivasyon sözünü girin:") + def add_custom_quote(self) -> None: + new_q = simpledialog.askstring("Add Discipline Maxim", "Enter a custom focus principle:", parent=self.root) if new_q and new_q.strip(): - self.settings["quotes"].append(new_q.strip()) - self.save_settings() - self.quote_box.config(text=f'"{new_q.strip()}"') - - # ---------------- TAB 5: SETTINGS ---------------- - def build_tab_settings(self): + cleaned = new_q.strip() + quotes = list(self.gui_prefs.get("quotes") or DEFAULT_QUOTES) + quotes.append(cleaned) + self.gui_prefs["quotes"] = quotes + self.save_gui_prefs() + self.quote_box.config(text=f'"{cleaned}"') + + # ---------------- TAB 5: SYSTEM SETTINGS ---------------- + def build_tab_settings(self) -> None: f = self.tab_settings card = tk.Frame(f, bg=THEME["surface0"], padx=24, pady=20) card.pack(fill="both", expand=True, padx=20, pady=20) - tk.Label(card, text="⚙️ SİSTEM VE ÇALIŞMA AYARLARI", - font=("Segoe UI Bold", 13), fg=THEME["green"], bg=THEME["surface0"]).pack(anchor="w", pady=(0, 20)) + tk.Label( + card, + text="SYSTEM & TIMER CONFIGURATION", + font=("Consolas", 11, "bold"), + fg=THEME["green"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(0, 18)) - # Time configs grid_f = tk.Frame(card, bg=THEME["surface0"]) - grid_f.pack(fill="x", pady=5) - - tk.Label(grid_f, text="Pomodoro Ders Süresi (dk):", font=("Segoe UI", 10), - fg=THEME["text"], bg=THEME["surface0"]).grid(row=0, column=0, sticky="w", pady=8) - self.spin_p_work = ttk.Spinbox(grid_f, from_=5, to=120, width=10) - self.spin_p_work.set(self.settings.get("pomo_work", 25)) - self.spin_p_work.grid(row=0, column=1, sticky="w", padx=15) - - tk.Label(grid_f, text="Pomodoro Mola Süresi (dk):", font=("Segoe UI", 10), - fg=THEME["text"], bg=THEME["surface0"]).grid(row=1, column=0, sticky="w", pady=8) - self.spin_p_break = ttk.Spinbox(grid_f, from_=1, to=30, width=10) - self.spin_p_break.set(self.settings.get("pomo_break", 5)) - self.spin_p_break.grid(row=1, column=1, sticky="w", padx=15) - - tk.Label(grid_f, text="Standart Mod Süresi (dk):", font=("Segoe UI", 10), - fg=THEME["text"], bg=THEME["surface0"]).grid(row=2, column=0, sticky="w", pady=8) + grid_f.pack(fill="x", pady=4) + + tk.Label( + grid_f, + text="Pomodoro Work Duration (min):", + font=("Segoe UI", 10), + fg=THEME["text"], + bg=THEME["surface0"], + ).grid(row=0, column=0, sticky="w", pady=8) + self.spin_p_work = ttk.Spinbox(grid_f, from_=5, to=180, width=10) + self.spin_p_work.set(int(self.gui_prefs.get("pomo_work", 25))) + self.spin_p_work.grid(row=0, column=1, sticky="w", padx=16) + + tk.Label( + grid_f, + text="Pomodoro Break Duration (min):", + font=("Segoe UI", 10), + fg=THEME["text"], + bg=THEME["surface0"], + ).grid(row=1, column=0, sticky="w", pady=8) + self.spin_p_break = ttk.Spinbox(grid_f, from_=1, to=60, width=10) + self.spin_p_break.set(int(self.gui_prefs.get("pomo_break", 5))) + self.spin_p_break.grid(row=1, column=1, sticky="w", padx=16) + + tk.Label( + grid_f, + text="Fixed Block Duration (min):", + font=("Segoe UI", 10), + fg=THEME["text"], + bg=THEME["surface0"], + ).grid(row=2, column=0, sticky="w", pady=8) self.spin_std = ttk.Spinbox(grid_f, from_=10, to=360, width=10) - self.spin_std.set(self.settings.get("standard_duration", 60)) - self.spin_std.grid(row=2, column=1, sticky="w", padx=15) - - # DNS Flush Action - tk.Button(card, text="🔄 DNS Önbelleğini Hemen Temizle (Flush DNS)", - command=self.action_flush_dns, - font=("Segoe UI Bold", 10), bg=THEME["surface1"], fg=THEME["sapphire"], - relief="flat", padx=14, pady=8, cursor="hand2").pack(anchor="w", pady=15) - - # Save Button - tk.Button(card, text="💾 Ayarları Kaydet", command=self.save_tab_settings, - font=("Segoe UI Bold", 11), bg=THEME["green"], fg=THEME["crust"], - relief="flat", padx=20, pady=8, cursor="hand2").pack(anchor="w", pady=10) + self.spin_std.set(int(self.gui_prefs.get("standard_duration", 60))) + self.spin_std.grid(row=2, column=1, sticky="w", padx=16) + + self.strict_var = tk.BooleanVar(value=bool(self.gui_prefs.get("strict_mode", True))) + tk.Checkbutton( + card, + text="Enable Strict Friction Challenge on early abort & window close", + variable=self.strict_var, + font=("Segoe UI Semibold", 10), + fg=THEME["text"], + bg=THEME["surface0"], + selectcolor=THEME["mantle"], + activebackground=THEME["surface0"], + activeforeground=THEME["green"], + ).pack(anchor="w", pady=(14, 6)) + + tk.Label( + card, + text=f"Unified State Directory: {self.state_dir}", + font=("Consolas", 9), + fg=THEME["subtext"], + bg=THEME["surface0"], + ).pack(anchor="w", pady=(4, 14)) + + action_row = tk.Frame(card, bg=THEME["surface0"]) + action_row.pack(anchor="w", pady=6) + + tk.Button( + action_row, + text="[SAVE SETTINGS]", + command=self.save_tab_settings, + font=("Segoe UI Bold", 10), + bg=THEME["green"], + fg=THEME["crust"], + relief="flat", + padx=18, + pady=8, + cursor="hand2", + ).pack(side="left", padx=(0, 10)) + + tk.Button( + action_row, + text="[FLUSH DNS CACHE]", + command=self.action_flush_dns, + font=("Segoe UI Bold", 10), + bg=THEME["surface1"], + fg=THEME["sapphire"], + relief="flat", + padx=16, + pady=8, + cursor="hand2", + ).pack(side="left") + + def action_elevate_admin(self) -> None: + if is_elevated(): + return + if self.is_active: + messagebox.showwarning("Session Active", "Stop the current session before elevating privileges.") + return + if elevate_self(script_path=os.path.abspath(__file__)): + self.worker_running = False + self.root.destroy() + else: + messagebox.showwarning("Elevation Cancelled", "Administrator UAC prompt was cancelled or declined.") - def action_flush_dns(self): - flush_dns() - messagebox.showinfo("DNS Temizlendi", "Windows DNS Çözümleyici Önbelleği başarıyla temizlendi.") + def action_flush_dns(self) -> None: + flush_dns_async() + messagebox.showinfo("DNS Cache Purge", "Asynchronous DNS resolver cache purge triggered.") - def save_tab_settings(self): + def save_tab_settings(self) -> None: + if self.is_active and self.is_strict_active() and not self.strict_var.get(): + self.strict_var.set(True) + messagebox.showwarning("Shield Locked", "Strict mode cannot be disabled during an active focus sprint.") + return try: - self.settings["pomo_work"] = int(self.spin_p_work.get()) - self.settings["pomo_break"] = int(self.spin_p_break.get()) - self.settings["standard_duration"] = int(self.spin_std.get()) - self.save_settings() - self.on_mode_change() - messagebox.showinfo("Başarılı", "Ayarlar kaydedildi.") - except Exception as e: - messagebox.showerror("Hata", f"Geçersiz değer: {e}") - - # ---------------- LOGIC & ENGINE INTEGRATION ---------------- - def toggle_session(self): + p_work = max(1, int(self.spin_p_work.get())) + p_break = max(1, int(self.spin_p_break.get())) + std_dur = max(1, int(self.spin_std.get())) + self.gui_prefs["pomo_work"] = p_work + self.gui_prefs["pomo_break"] = p_break + self.gui_prefs["standard_duration"] = std_dur + self.gui_prefs["strict_mode"] = True if self.current_profile == "hardcore" else bool(self.strict_var.get()) + self.save_gui_prefs() + if not self.is_active: + self.on_mode_change() + messagebox.showinfo("Saved", "Configuration updated.") + except Exception as exc: + messagebox.showerror("Invalid Input", f"Could not save settings:\n{exc}") + + # ---------------- SESSION LIFECYCLE & ENGINE INTEGRATION ---------------- + def _set_controls_locked_for_session(self, active: bool) -> None: + rb_state = "disabled" if active else "normal" + for rb in (*self.mode_radios, *self.profile_radios): + rb.config(state=rb_state) + + def _verify_friction_challenge(self, reason: str = "STRICT SESSION UNLOCK") -> bool: + dlg = FrictionChallengeDialog(self.root, reason_label=reason) + self.root.wait_window(dlg) + return dlg.passed + + def toggle_session(self) -> None: if not self.is_active: self.start_session() else: - self.stop_session() + self.stop_session(verified=False) - def start_session(self): - if not is_admin(): - messagebox.showwarning("Yönetici Yetkisi Gerekli", - "Hosts dosyasını engellemek için FocusFlow'un Yönetici (Administrator) olarak çalıştırılması önerilir.\nKorumasız modda devam edilecek.") + def start_session(self) -> None: + prof = load_or_default(self.current_profile, state_dir=self.state_dir) + self.active_profile_obj = prof - # Determine duration m = self.mode_var.get() if m == "pomodoro": - mins = self.settings.get("pomo_work", 25) + mins = int(self.gui_prefs.get("pomo_work", prof.default_work_minutes)) self.pomo_state = "WORK" - self.lbl_pomo_badge.config(text=f"POMODORO DÖNGÜ {self.pomo_cycle} (DERS)", fg=THEME["green"]) + self.lbl_pomo_badge.config( + text=f"POMODORO CYCLE {self.pomo_cycle} // {prof.name.upper()}", + fg=THEME["green"], + ) elif m == "standard": - mins = self.settings.get("standard_duration", 60) - self.lbl_pomo_badge.config(text="STANDART ODAK SEANSI", fg=THEME["sapphire"]) + mins = int(self.gui_prefs.get("standard_duration", 60)) + self.pomo_state = "WORK" + self.lbl_pomo_badge.config(text=f"DEEP WORK // {prof.name.upper()}", fg=THEME["sapphire"]) else: - mins = 120 - self.lbl_pomo_badge.config(text="ESNEK SERBEST MOD", fg=THEME["peach"]) - - self.remaining_seconds = mins * 60 - self.total_session_seconds = self.remaining_seconds + mins = int(self.gui_prefs.get("flex_duration", 90)) + self.pomo_state = "WORK" + self.lbl_pomo_badge.config(text=f"EXTENDED // {prof.name.upper()}", fg=THEME["peach"]) + + self.active_planned_minutes = mins + self.session_blocked_count = 0 + self.lbl_mini_blocked.config(text="Session Blocks: 0") + + now_utc = datetime.datetime.now(datetime.timezone.utc) + self.active_session_start_utc = now_utc + self.active_session_id = generate_session_id() + self.session_store.start_session( + session_id=self.active_session_id, + profile=prof.name, + planned_minutes=mins, + start_time=now_utc, + ) + + strict_level = self.current_strictness_level() + with self._supervisor_lock: + self._proc_supervisor = ProcessSupervisor(prof.blocked_processes) + self._anticheat_guard = AntiCheatGuard(strict_level) + + self.phase_timer.start(mins * 60, phase="WORK") self.is_active = True - self.is_paused = False + self._set_controls_locked_for_session(True) - # Generate emergency unlock code - self.emergency_code = str(random.randint(100000, 999999)) + self._engage_work_shield(mins) - # Engage atomic hosts block - self._engage_hosts_block() - - # Update UI Controls - self.btn_toggle.config(text="⏹️ PLANI DURDUR", bg=THEME["red"], fg=THEME["crust"]) - self.btn_break.config(state="normal") + self.btn_toggle.config(text="[STOP SESSION]", bg=THEME["red"], fg=THEME["crust"]) + break_state = "disabled" if self.current_profile == "hardcore" else "normal" + self.btn_break.config(text="[TAKE BREAK]", fg=THEME["yellow"], state=break_state) self.btn_emergency.config(state="normal") - self.lbl_status.config(text="🔒 Kalkan Devrede — Tüm Dikkat Dağıtıcılar Engellendi", fg=THEME["green"]) - - def stop_session(self): - if self.settings.get("strict_mode", True) and self.remaining_seconds > 0: - prompt = simpledialog.askstring("Tavizsiz Mod Koruması", - f"Erken bitirmek için aşağıdaki acil durum onay kodunu girin:\n\n{self.emergency_code}") - if prompt != self.emergency_code: - messagebox.showerror("Yetkisiz", "Onay kodu hatalı! Odaklanmaya devam ediliyor.") - return - self._release_hosts_block() - self.is_active = False - self.btn_toggle.config(text="🔒 ODAKLANMAYI BAŞLAT", bg=THEME["green"], fg=THEME["crust"]) - self.btn_break.config(state="disabled") - self.btn_emergency.config(state="disabled") - self.lbl_status.config(text="● Kalkan Kaldırıldı — Sistem Serbest", fg=THEME["subtext"]) - self.on_mode_change() - - def give_break(self): - if not self.is_active: - return - if self.pomo_state == "WORK": - self.pomo_state = "BREAK" - mins = self.settings.get("pomo_break", 5) - self.remaining_seconds = mins * 60 - self.total_session_seconds = self.remaining_seconds - self._release_hosts_block() - self.lbl_pomo_badge.config(text=f"MOLA VAKTİ ({mins} DK)", fg=THEME["blue"]) - self.lbl_status.config(text="☕ Mola zamanı — Rahatla ve nefes al", fg=THEME["blue"]) - self.btn_break.config(text="▶️ DERSE DÖN", fg=THEME["green"]) - else: - self.pomo_state = "WORK" - self.pomo_cycle += 1 - mins = self.settings.get("pomo_work", 25) - self.remaining_seconds = mins * 60 - self.total_session_seconds = self.remaining_seconds - self._engage_hosts_block() - self.lbl_pomo_badge.config(text=f"POMODORO DÖNGÜ {self.pomo_cycle} (DERS)", fg=THEME["green"]) - self.lbl_status.config(text="🔒 Kalkan Devrede — Masaya dönüldü", fg=THEME["green"]) - self.btn_break.config(text="☕ MOLA VER", fg=THEME["yellow"]) - - def prompt_emergency(self): - prompt = simpledialog.askstring("Acil Durum Kilidi", - f"Kalkanı hemen kaldırmak için aşağıdaki acil durum kodunu girin:\n\n{self.emergency_code}") - if prompt == self.emergency_code: - self.stop_session() + def _engage_work_shield(self, duration_minutes: int) -> None: + prof = self.active_profile_obj + all_domains = [*prof.blocked_domains, *DOH_BYPASS_DOMAINS] + now_utc = datetime.datetime.now(datetime.timezone.utc) + meta = SessionMeta( + session_id=self.active_session_id, + pid=os.getpid(), + started_at=now_utc, + expected_end_at=now_utc + datetime.timedelta(minutes=max(1, duration_minutes)), + profile=prof.name, + ) + with self._supervisor_lock: + self._active_sinkhole_domains = all_domains + self._active_session_meta = meta + + self.hosts_engaged = False + try: + if self.hosts_manager.apply_blocklist(all_domains, meta=meta): + self.hosts_engaged = True + flush_dns_async() + except OSError: + self.hosts_engaged = False + + if self.hosts_engaged: + self.lbl_status.config( + text="[ACTIVE] FULL SHIELD [HOSTS + PROC] — Dual-stack sinkhole & supervisor engaged", + fg=THEME["green"], + ) else: - messagebox.showerror("Hata", "Kod eşleşmedi!") - - def _engage_hosts_block(self): - sites = self.settings.get("sites", []) - if not sites or not is_admin(): + self.lbl_status.config( + text="[ACTIVE] PROCESS-ONLY [UNPRIVILEGED] — Process guard active (elevate for hosts sinkhole)", + fg=THEME["yellow"], + ) + + def _release_work_shield_async(self) -> None: + was_engaged = self.hosts_engaged + self.hosts_engaged = False + with self._supervisor_lock: + self._active_sinkhole_domains = [] + self._active_session_meta = None + + if not was_engaged: return - try: - with open(HOSTS_PATH, "r", encoding="utf-8", errors="ignore") as f: - content = f.read() - - block_marker_start = "# --- FOCUSFLOW BLOCK START ---" - block_marker_end = "# --- FOCUSFLOW BLOCK END ---" - if block_marker_start in content: - # Remove existing block first - p1 = content.find(block_marker_start) - p2 = content.find(block_marker_end) + len(block_marker_end) - content = content[:p1] + content[p2:] + def _worker() -> None: + try: + self.hosts_manager.rollback() + except Exception: + pass + flush_dns_async() - new_block = [block_marker_start] - for s in sites: - new_block.append(f"{REDIRECT_IP} {s}") - new_block.append(f"{REDIRECT_IP} www.{s}") - new_block.append(block_marker_end) + threading.Thread(target=_worker, name="FocusFlowHostsRollback", daemon=True).start() - with open(HOSTS_PATH, "w", encoding="utf-8") as f: - f.write(content.strip() + "\n\n" + "\n".join(new_block) + "\n") + def stop_session(self, verified: bool = False, completed: bool = False) -> bool: + if not self.is_active: + return True - flush_dns() - except Exception: - pass + if not completed and not verified and self.pomo_state == "WORK" and self.is_strict_active(): + if not self._verify_friction_challenge("CONFIRM EARLY SESSION ABORT"): + return False - def _release_hosts_block(self): - if not is_admin(): - return - try: - if not os.path.exists(HOSTS_PATH): - return - with open(HOSTS_PATH, "r", encoding="utf-8", errors="ignore") as f: - content = f.read() - - block_marker_start = "# --- FOCUSFLOW BLOCK START ---" - block_marker_end = "# --- FOCUSFLOW BLOCK END ---" - - if block_marker_start in content and block_marker_end in content: - p1 = content.find(block_marker_start) - p2 = content.find(block_marker_end) + len(block_marker_end) - cleaned = content[:p1].rstrip() + "\n" + content[p2:].lstrip() - with open(HOSTS_PATH, "w", encoding="utf-8") as f: - f.write(cleaned) - - flush_dns() - except Exception: - pass - - def _clock_worker(self): - while self.timer_running: - time.sleep(1) - if self.is_active and not self.is_paused: - if self.remaining_seconds > 0: - self.remaining_seconds -= 1 - mins = self.remaining_seconds // 60 - secs = self.remaining_seconds % 60 - time_str = f"{mins:02d}:{secs:02d}" + elapsed_min = max(0, self.phase_timer.elapsed_seconds() // 60) + if completed: + recorded_min = self.active_planned_minutes + else: + recorded_min = elapsed_min + + if self.active_session_id: + self.session_store.finalize_session( + session_id=self.active_session_id, + profile=self.current_profile, + duration_minutes=recorded_min, + completed=completed, + blocked_count=self.session_blocked_count, + status="completed" if completed else "aborted", + start_time=self.active_session_start_utc, + ) + self.active_session_id = "" + self.active_session_start_utc = None + + self.phase_timer.stop() + self.is_active = False + self.pomo_state = "WORK" + self._release_work_shield_async() + self._set_controls_locked_for_session(False) - ratio = self.remaining_seconds / max(1, self.total_session_seconds) + self.btn_toggle.config(text="[START FOCUS]", bg=THEME["green"], fg=THEME["crust"]) + self.btn_break.config(text="[TAKE BREAK]", fg=THEME["yellow"], state="disabled") + self.btn_emergency.config(state="disabled") + self.lbl_status.config(text="[STANDBY] Shield disengaged — unrestricted system access", fg=THEME["subtext"]) + self.on_mode_change() + self.refresh_analytics_ui() + return True - # Update GUI safely - self.root.after(0, lambda t=time_str, r=ratio: self._update_clock_ui(t, r)) - else: - self.root.after(0, self._on_session_timer_expired) + def prompt_emergency(self) -> None: + if not self.is_active: + return + if self._verify_friction_challenge("EMERGENCY SHIELD OVERRIDE"): + self.stop_session(verified=True, completed=False) - def _update_clock_ui(self, time_str, ratio): + def give_break(self) -> None: + if not self.is_active: + return + if self.pomo_state == "WORK": + if self.is_strict_active() and not self.phase_timer.awaiting_transition: + if not self._verify_friction_challenge("EARLY BREAK REQUEST"): + return + self._enter_break_phase() + else: + self._enter_next_work_phase() + + def _enter_break_phase(self) -> None: + self.pomo_state = "BREAK" + mins = int(self.gui_prefs.get("pomo_break", 5)) + self._release_work_shield_async() + self.phase_timer.start(mins * 60, phase="BREAK") + self.lbl_pomo_badge.config(text=f"RECOVERY BREAK ({mins} MIN)", fg=THEME["blue"]) + self.lbl_timer.config(fg=THEME["blue"]) + self.lbl_status.config(text="[BREAK] Hosts unlocked — step away from the screen", fg=THEME["blue"]) + self.btn_break.config(text="[RESUME WORK]", fg=THEME["green"], state="normal") + + def _enter_next_work_phase(self) -> None: + self.pomo_state = "WORK" + self.pomo_cycle += 1 + prof = load_or_default(self.current_profile, state_dir=self.state_dir) + self.active_profile_obj = prof + mins = int(self.gui_prefs.get("pomo_work", prof.default_work_minutes)) + self.active_planned_minutes = mins + self.session_blocked_count = 0 + + now_utc = datetime.datetime.now(datetime.timezone.utc) + self.active_session_start_utc = now_utc + self.active_session_id = generate_session_id() + self.session_store.start_session( + session_id=self.active_session_id, + profile=prof.name, + planned_minutes=mins, + start_time=now_utc, + ) + + self.phase_timer.start(mins * 60, phase="WORK") + self._engage_work_shield(mins) + self.lbl_pomo_badge.config( + text=f"POMODORO CYCLE {self.pomo_cycle} // {prof.name.upper()}", + fg=THEME["green"], + ) + self.lbl_timer.config(fg=THEME["green"]) + break_state = "disabled" if self.current_profile == "hardcore" else "normal" + self.btn_break.config(text="[TAKE BREAK]", fg=THEME["yellow"], state=break_state) + + def _clock_worker(self) -> None: + while self.worker_running: + time.sleep(0.25) + if not self.is_active or self.phase_timer.awaiting_transition: + continue + + if self.phase_timer.poll_expired(): + self.root.after(0, self._on_phase_expired) + continue + + rem = self.phase_timer.remaining_seconds() + mins = rem // 60 + secs = rem % 60 + time_str = f"{mins:02d}:{secs:02d}" + ratio = self.phase_timer.progress_ratio() + self.root.after(0, lambda t=time_str, r=ratio: self._update_clock_ui(t, r)) + + def _update_clock_ui(self, time_str: str, ratio: float) -> None: + if not self.is_active: + return self.lbl_timer.config(text=time_str) self.draw_progress_bar(ratio) - def _on_session_timer_expired(self): + def _on_phase_expired(self) -> None: + if not self.is_active: + return + if self.current_mode == "pomodoro": if self.pomo_state == "WORK": - self.give_break() - messagebox.showinfo("Tebrikler!", "Ders seansı tamamlandı! Mola vakti.") + # Record completed sprint & release hosts BEFORE modal; start break timer AFTER modal closes! + if self.active_session_id: + self.session_store.finalize_session( + session_id=self.active_session_id, + profile=self.current_profile, + duration_minutes=self.active_planned_minutes, + completed=True, + blocked_count=self.session_blocked_count, + status="completed", + start_time=self.active_session_start_utc, + ) + self.active_session_id = "" + self.active_session_start_utc = None + self._release_work_shield_async() + self.lbl_timer.config(text="00:00") + self.draw_progress_bar(0.0) + self.refresh_analytics_ui() + messagebox.showinfo( + "Work Sprint Complete", + "Focus sprint recorded. Click OK to begin your recovery break.", + parent=self.root, + ) + if self.is_active: + self._enter_break_phase() else: - self.give_break() - messagebox.showinfo("Mola Bitti", "Mola bitti! Yeni odak seansı başlıyor.") + self.lbl_timer.config(text="00:00") + self.draw_progress_bar(0.0) + messagebox.showinfo( + "Break Finished", + "Recovery break complete. Click OK to start the next focus cycle.", + parent=self.root, + ) + if self.is_active: + self._enter_next_work_phase() else: - self.stop_session() - messagebox.showinfo("Seans Tamamlandı", "Hedeflenen çalışma süresi başarıyla bitti!") - - def _process_supervisor(self): - while self.timer_running: - time.sleep(2) - if self.is_active and self.pomo_state == "WORK" and HAS_PSUTIL: - blocked_apps = [a.lower() for a in self.settings.get("apps", [])] + self.stop_session(verified=True, completed=True) + messagebox.showinfo( + "Session Complete", + "Deep work session completed and recorded.", + parent=self.root, + ) + + def _supervisor_worker(self) -> None: + tick = 0 + while self.worker_running: + time.sleep(2.0) + if not self.is_active or self.pomo_state != "WORK": + continue + + tick += 1 + with self._supervisor_lock: + sup = self._proc_supervisor + ac = self._anticheat_guard + domains = list(self._active_sinkhole_domains) + meta = self._active_session_meta + strict_level = self.current_strictness_level() + + hits = 0 + try: + killed = sup.scan_and_terminate() + ac_killed = ac.enforce() + hits += len(killed) + len(ac_killed) + except Exception: + pass + + # Periodic mid-session hosts tamper watchdog in standard & hardcore modes + if self.hosts_engaged and domains and strict_level in ("standard", "hardcore") and tick % 3 == 0: try: - for proc in psutil.process_iter(["pid", "name"]): - p_name = proc.info["name"] - if p_name and p_name.lower() in blocked_apps: - try: - proc.kill() - self.blocked_attempts_count += 1 - self.root.after(0, self._update_blocked_counter) - except Exception: - pass + if self.hosts_manager.verify_or_reapply(domains, meta=meta): + hits += 1 + flush_dns_async() except Exception: pass - def _update_blocked_counter(self): - self.lbl_mini_blocked.config(text=f"Engellenen Girişim: {self.blocked_attempts_count}") + if hits > 0: + self.session_blocked_count += hits + self.root.after(0, self._update_blocked_counter) + + def _update_blocked_counter(self) -> None: + self.lbl_mini_blocked.config(text=f"Session Blocks: {self.session_blocked_count}") - def on_close(self): + def on_close(self) -> None: if self.is_active: - if not messagebox.askyesno("Çıkış Onayı", "Odaklanma oturumu hala aktif! Çıkmak istiyor musunuz?"): - return - self._release_hosts_block() - self.timer_running = False + if self.pomo_state == "WORK" and self.is_strict_active(): + if not self._verify_friction_challenge("WINDOW CLOSE DURING STRICT SPRINT"): + return + else: + if not messagebox.askyesno( + "Confirm Exit", + "An active session is in progress. Abort session and exit FocusFlow?", + parent=self.root, + ): + return + + if self.active_session_id: + elapsed_min = max(0, self.phase_timer.elapsed_seconds() // 60) + self.session_store.finalize_session( + session_id=self.active_session_id, + profile=self.current_profile, + duration_minutes=elapsed_min, + completed=False, + blocked_count=self.session_blocked_count, + status="aborted", + start_time=self.active_session_start_utc, + ) + self.active_session_id = "" + if self.hosts_engaged: + try: + self.hosts_manager.rollback() + except Exception: + pass + flush_dns_async() + + self.worker_running = False self.root.destroy() -def main(): +def main() -> None: + if "--elevate" in sys.argv and not is_elevated(): + if elevate_self(script_path=os.path.abspath(__file__)): + return + configure_windows_dpi() root = tk.Tk() - app = FocusFlowGUI(root) + FocusFlowGUI(root) root.mainloop() if __name__ == "__main__": main() - diff --git a/Launch_FocusFlow_GUI.bat b/Launch_FocusFlow_GUI.bat index 0c841f6..425ba74 100644 --- a/Launch_FocusFlow_GUI.bat +++ b/Launch_FocusFlow_GUI.bat @@ -1,6 +1,12 @@ @echo off -title FocusFlow v2.0 - Starting GUI... +setlocal +title FocusFlow v2.1.0 - Desktop HUD Launcher cd /d "%~dp0" -start "" pythonw FocusFlowGUI.py -exit +where pythonw >nul 2>nul +if %ERRORLEVEL% EQU 0 ( + start "" pythonw "%~dp0FocusFlowGUI.py" %* +) else ( + start "" python "%~dp0FocusFlowGUI.py" %* +) +exit /b 0 diff --git a/README.md b/README.md index 7dc402f..5806e6e 100644 --- a/README.md +++ b/README.md @@ -1,130 +1,164 @@ -# FocusFlow V2 +# FocusFlow v2.1

- FocusFlow V2 Banner + FocusFlow Banner

- High-Performance Deep Work Discipline Engine, Atomic Hosts Blocker & Catppuccin Mocha Desktop HUD.
- Engineered for developers, students, and professionals who demand uncompromising focus without digital sabotage. + Crash-Safe Deep Work Discipline Engine, Dual-Stack Atomic Hosts Blocker & Catppuccin Mocha Desktop HUD.
+ Engineered in Go and Python (zero external runtime dependencies) for developers, students, and operators who demand uncompromising focus without network corruption.

CI Status Release - Go Native - Modern GUI + Go Native CLI + Catppuccin Mocha HUD License: MIT - Platform - Memory Footprint - Atomic Rollback - Anti-DoH + Write-Ahead Journal + Dual-Stack Anti-DoH

--- -## Why FocusFlow V2? (The Paradigm Shift) +## Why FocusFlow v2.1? -Traditional site blockers and browser extensions are easily bypassed: -1. **Easy Browser Disabling:** Extensions can be disabled in two clicks via incognito mode or developer settings. -2. **DNS-over-HTTPS (DoH) Leaks:** Modern browsers (Chrome, Brave, Edge) bypass local `hosts` files by resolving DNS through encrypted cloud resolvers (`cloudflare-dns.com`, `dns.google`). -3. **Hosts File Corruption:** Primitive scripts write directly to `C:\Windows\System32\drivers\etc\hosts`. If the system crashes, reboots, or loses power, internet connectivity is permanently broken. -4. **Resource Hogging:** Electron/Python blockers often consume 200MB+ RAM and 5-10% CPU constantly iterating process trees. +Conventional website blockers and browser extensions fail under real-world conditions: +1. **Trivial Extension Bypass:** Browser extensions can be disabled in seconds or bypassed via private windows and secondary browsers. +2. **IPv6 & DNS-over-HTTPS (DoH) Leaks:** Single-stack `127.0.0.1` blockers leak traffic over IPv6 (`AAAA`) records and encrypted browser DoH resolvers (`cloudflare-dns.com`, `dns.google`, `dns.quad9.net`, `dns.nextdns.io`). +3. **Hosts File & ACL Corruption:** Naive scripts overwrite `C:\Windows\System32\drivers\etc\hosts` in place without write-ahead journaling or Windows DACL preservation—breaking DNS resolution after power loss, crashes, or reboots. +4. **Heavy Runtime Dependencies:** Typical desktop wrappers pull hundreds of megabytes of packages just to enumerate processes. -**FocusFlow V2 solves all of this at the native operating system layer:** -* **SHA-256 Atomic Rollback:** Backs up the hosts file before every sprint. Atomic file swapping guarantees your original network configuration is restored 100% cleanly, even during unexpected shutdowns. -* **Zero-Overhead Win32 Scanning:** Replaces high-overhead pollers with low-level Win32 `CreateToolhelp32Snapshot` calls, consuming **<4 MB RAM** and **0.0% idle CPU**. -* 🎨 **Catppuccin Mocha High-DPI Desktop GUI:** A sleek, modern dark HUD with real-time Pomodoro timers, weekly bar charts, custom blocklists, and motivation cards. -* **Automatic Anti-DoH & DNS Flushing:** Automatically flushes the local resolver cache (`ipconfig /flushdns`) and restricts known DoH bypass endpoints during focus sessions. -* **Persistent Analytics:** Tracks completed sprints, streak days, total deep work hours, and distraction blocks locally. +**FocusFlow v2.1 solves these failure modes at the operating-system boundary:** +* **Unified Go CLI + Zero-Dependency Python HUD:** `cmd/focusflow` (Go) and `FocusFlowGUI.py` + `focusflow_core/` (Python stdlib + Win32 `ctypes`) share the exact same state directory, `config.json`, `sessions.json`, `hosts.focusflow.journal.json`, and managed block markers. +* **Write-Ahead SHA-256 Rollback Journal & Auto-Recovery:** Strips any prior managed blocks before computing a clean baseline SHA-256 backup, persists `hosts.focusflow.journal.json` before touching `hosts`, preserves Windows DACLs via `ReplaceFileW` (`NetworkService` / `Users` read permissions remain intact), and automatically recovers orphaned crash/reboot states on startup (`RecoverIfOrphaned`). +* **Dual-Stack IPv4 + IPv6 Sinkhole & Expanded Anti-DoH:** Blocks both `0.0.0.0` and `::` (including `www.` subdomains) alongside major DoH bypass endpoints, with mid-session tamper verification and non-blocking DNS cache flushing. +* **Hardened Native Process Supervisor:** Uses Win32 `CreateToolhelp32Snapshot` (`Process32FirstW`/`Process32NextW`) on Windows (zero `psutil` required) and direct `/proc` inspection on Linux (resolving 15-byte `TASK_COMM_LEN` truncation without spawning `ps` every second), guarded by a strict critical system/host process denylist. +* **High-Friction Strict Mode & Genuine Telemetry:** Features a non-pasteable 16-character alphanumeric Friction Challenge, `time.monotonic()` zero-drift countdowns, Per-Monitor v2 High-DPI Catppuccin Mocha HUD, and real streak/completion analytics exported to JSON, CSV, or PNG. --- ## Architecture ```text -┌──────────────────────────────────────────────────────────────┐ -│ FocusFlow V2 Desktop GUI / CLI Terminal │ -└──────────────────────────────┬───────────────────────────────┘ - │ - ┌──────────────────────┼───────────────────────┐ - ▼ ▼ ▼ - ┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ - │ Hosts Engine │ │ Win32 Killer │ │ Session Metrics │ - │ (Atomic/SHA) │ │ (<4MB RAM) │ │ (%APPDATA% JSON)│ - └──────┬───────┘ └──────┬───────┘ └─────────────────┘ - │ │ - ▼ ▼ - [System Hosts File] [Target Procs] - (Auto-Rollback) (Terminated) ++----------------------------------------------------------------------+ +| FocusFlow v2.1 CLI (Go) <==> Desktop HUD (Python/Tk) | ++-----------------------------------+----------------------------------+ + | + Shared State (%APPDATA%\FocusFlow or $FOCUSFLOW_HOME) + [config.json | sessions.json | hosts.focusflow.journal.json] + | + +---------------------------+---------------------------+ + | | | + v v v ++------------------+ +-------------------+ +--------------------+ +| Dual-Stack Hosts | | Native Supervisor | | Real-Time Metrics | +| SHA-256 + Journal| | Win32 / Linux proc| | Streak, JSON & CSV | ++--------+---------+ +---------+---------+ +--------------------+ + | | + v v + [System hosts File] [Blocked Processes] + (ACL-Safe Swap) (Denylist-Guarded) ``` --- ## Quick Start -### 1. Graphical Interface (GUI) -Simply launch `Launch_FocusFlow_GUI.bat` or run: +### 1. Desktop HUD (Python 3.10+, Zero Required Packages) +Launch `Launch_FocusFlow_GUI.bat` on Windows or run directly: ```bash -pythonw FocusFlowGUI.py +python FocusFlowGUI.py ``` +To launch directly with Administrator elevation prompt on Windows: +```bash +python FocusFlowGUI.py --elevate +``` +*(Optional)* For PNG chart card rendering, install `Pillow`: `pip install .[reports]`. -### 2. Standalone Native Binary (CLI) -Compile directly from source with Go: +### 2. Native Standalone CLI (Go 1.23+) ```bash -go build -ldflags="-s -w" -o focusflow.exe ./cmd/focusflow +CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.Version=2.1.0" -o focusflow ./cmd/focusflow ``` --- -## CLI Usage +## CLI Reference -> **Note:** Modifying system hosts files requires administrative privileges. Run terminal as **Administrator**. +> **Privilege Model:** Modifying the system `hosts` file requires Administrator (`Windows`) or `root` (`Linux`/`macOS`) privileges. When run unprivileged, FocusFlow honestly reports `PROCESS-ONLY [UNPRIVILEGED]` rather than claiming `hosts` is locked. Pass `--elevate` to request privilege elevation. ```bash -# Launch interactive terminal TUI menu +# Launch interactive terminal dashboard focusflow menu -# Start a 50-minute Developer sprint (keeps GitHub & Docs open) -focusflow start --profile dev --minutes 50 +# Start a 50-minute Developer sprint (elevating via UAC/sudo if needed) +focusflow start --profile dev --minutes 50 --elevate -# Start a 25-minute Academic Study sprint (YKS/KPSS/Exam mode) +# Start a 25-minute Study sprint or Hardcore Aegis sprint focusflow start --profile study --minutes 25 +focusflow start --profile hardcore --strict hardcore -# Check current blocker status +# Inspect shield capability, hosts status, and active journal (human or JSON) focusflow status +focusflow status --json -# Immediate rollback & restore internet -focusflow stop +# Manage custom RFC-1123 domains and denylist-checked executables +focusflow list --json +focusflow add site reddit.com +focusflow add app steam.exe +focusflow remove site reddit.com -# Purge local DNS cache immediately -focusflow flush +# View genuine focus hours, completion rate, active streak, and 7-day ASCII chart +focusflow stats --days 7 +focusflow stats --days 7 --json -# View lifetime productivity metrics -focusflow stats +# Export telemetry to JSON or CSV +focusflow export --format json --out focus_report.json +focusflow export --format csv --out focus_sessions.csv + +# Run system diagnostics or recover orphaned crash/reboot state +focusflow doctor +focusflow doctor --json +focusflow recover --elevate + +# Immediate rollback & DNS cache flush +focusflow stop +focusflow flush ``` --- ## Built-in Profiles -| Profile | Target Audience | Allowed Resources | Blocked Distractions | +| Profile | Default Interval | Target Workflow | Active Protections | | :--- | :--- | :--- | :--- | -| **`dev`** | Software Engineers | GitHub, GitLab, StackOverflow, Docs.rs, MDN | Twitter/X, Instagram, TikTok, Reddit, Netflix, Twitch, Discord, Steam | -| **`study`** | Students & Researchers | Educational portals, LMS, Academic sites | YouTube, TikTok, Kick, Netflix, Gaming launchers, Chat clients | -| **`hardcore`** | Deep Work Purists | Specified whitelist only | All distractions + Task Manager / Terminal kill prevention | +| **`study`** | `25m / 5m` | Academic & Exam Prep | Blocks video, social, streaming, chat clients, and game launchers | +| **`dev`** | `50m / 10m` | Software Engineering | Keeps GitHub, StackOverflow & technical docs open; blocks social & gaming | +| **`hardcore`** | `25m / 5m` | Aegis Lockdown | Study blocklist + strict Friction Challenge + Anti-Cheat task-manager suppression (`taskmgr.exe`, `SystemInformer.exe`, `processhacker.exe`) | --- -## Safety & Integrity Guarantee +## Crash Safety & System Integrity -FocusFlow V2 is engineered with an atomic safety-first philosophy: -* Before any modification, the original `hosts` file is copied to `hosts.focusflow.bak` and verified via a SHA-256 checksum. -* On session completion, interrupt (`Ctrl+C`), or `focusflow stop`, the backup file is restored and the DNS resolver cache is cleared immediately. +* **Clean Baseline Guarantee:** FocusFlow strips any current or legacy managed blocks before hashing and writing `hosts.focusflow.bak`, ensuring a contaminated `hosts` file is never backed up. +* **Write-Ahead Rollback Journal:** `hosts.focusflow.journal.json` records `original_sha256`, `backup_path`, `hosts_path`, `session_id`, `pid`, `started_at`, `expected_end_at`, and `profile` prior to any `hosts` write. +* **Automatic Startup Recovery:** On every CLI or GUI startup, `RecoverIfOrphaned` checks whether a prior session crashed, rebooted, or expired; verifies `.bak` against `original_sha256` (falling back to deterministic marker stripping if `.bak` was altered); restores `hosts` while preserving OS permissions/ACLs; and marks the interrupted session `completed: false` in `sessions.json`. +* **Critical Process Denylist:** Kernel, session, shell, and host binaries (`csrss.exe`, `lsass.exe`, `svchost.exe`, `explorer.exe`, `dwm.exe`, `winlogon.exe`, `python.exe`, `pythonw.exe`, `focusflow.exe`, `wt.exe`, PIDs `0`/`4`/self/parent) can never be added or terminated. + +--- + +## Testing + +All Go and Python tests run hermetically inside temporary `FOCUSFLOW_HOME` and `FOCUSFLOW_HOSTS_PATH` sandboxes—never touching your real `%APPDATA%` or system `hosts` file: + +```bash +go vet ./... +go test -v ./... +python -m pytest -v +``` --- ## License -This project is open-source under the [MIT License](LICENSE). -Created with passion by [aloneangel45](https://github.com/aloneangel45). +Released under the [MIT License](LICENSE) by [aloneangel45](https://github.com/aloneangel45). diff --git a/README.tr.md b/README.tr.md index 125e94f..0dbcff6 100644 --- a/README.tr.md +++ b/README.tr.md @@ -1,54 +1,95 @@ -# ⚡ FocusFlow V2 (Türkçe Kılavuz) +# FocusFlow v2.1 (Turkce Kullanim ve Mimari Kilavuzu)

- Rust ile geliştirilmiş, Kernel seviyesinde derin odaklanma motoru, atomik hosts engelleyicisi ve ultra hafif Win32 proses denetleyicisi. + Cokmeye Karsi Korumali Derin Odaklanma Motoru, Cift Yiginli (IPv4/IPv6) Atomik Hosts Engelleyicisi ve Catppuccin Mocha Masaustu HUD.

--- -## 🚀 FocusFlow V2 ile Neler Değişti? +## FocusFlow v2.1 Mimarisi ve Yenilikler -Eski Python versiyonu (V1) harika bir prototipti; ancak V2 ile birlikte sistem tamamen **Rust** ile baştan kodlandı: +FocusFlow v2.1, **Go (yerel CLI motoru)** ve **Python standart kutuphanesi (`focusflow_core` + `FocusFlowGUI.py`, sifir zorunlu harici bagimlilik)** uzerinde tamamen birlestirilmis bir sistem mimarisi sunar: -1. **Sıfır İnternet Bozulma Riski (Atomic Rollback):** - * Eski sistemde elektrik kesilse veya program kapansa hosts dosyası bozulabiliyordu. - * V2'de **SHA-256 hash kontrollü yedekleme** ve atomik dosya takası kullanılır. Program çöktüğü veya kapandığı an orijinal hosts dosyası %100 temiz şekilde geri yüklenir. -2. **DNS-over-HTTPS (DoH) Koruması:** - * Modern tarayıcılar (Chrome, Brave, Edge) DNS-over-HTTPS ile hosts dosyasını delebiliyordu. - * V2, yerel DNS önbelleğini (`ipconfig /flushdns`) otomatik temizler ve DoH kaçış noktalarını kilitler. -3. **<4MB Bellek & %0 CPU:** - * Python runtime'ı ve ağır `psutil` döngüleri yerine doğrudan Windows Win32 API (`CreateToolhelp32Snapshot`) kullanılır. Sistem boştayken hissedilmez bile. -4. **Hazır Profiller:** - * `focusflow start --profile dev` (Yazılımcı modu: GitHub, StackOverflow, Docs açık; sosyal medya kapalı) - * `focusflow start --profile study` (YKS/KPSS/Sınav modu: Oyunlar, Discord, TikTok, YouTube kilitli) - * `focusflow start --profile hardcore` (Aegis kilidi: Görev Yöneticisi engellemesi açık) +1. **Ortak Durum ve Yapilandirma Katmani:** + * Hem Go CLI (`focusflow`) hem de Python masaustu arayuzu (`FocusFlowGUI.py`) ayni durum dizinini (`FOCUSFLOW_HOME` -> Windows'ta `%APPDATA%\FocusFlow`, Linux/macOS'ta `~/.config/focusflow`), ayni `config.json`, `sessions.json` ve `hosts.focusflow.journal.json` semalarini kullanir. +2. **SHA-256 Write-Ahead Journal ve Otomatik Kurtarma (`RecoverIfOrphaned`):** + * `hosts` dosyasina dokunmadan once mevcut FocusFlow bloklari temizlenerek saf temel kopyanin SHA-256 ozeti alinir (`hosts.focusflow.bak`) ve `hosts.focusflow.journal.json` diske yazilir. + * Elektrik kesintisi, sistem cokmesi veya yeniden baslatma sonrasinda CLI ya da GUI acildiginda yetim oturum otomatik tespit edilir; SHA-256 dogrulamasi (veya deterministik isaretci temizligi) ile `hosts` dosyasi Windows ACL izinleri (`ReplaceFileW`) korunarak geri yuklenir. +3. **Cift Yiginli IPv4 + IPv6 Sinkhole ve Gelismis Anti-DoH:** + * Yalnizca `0.0.0.0` degil, `::` (IPv6) kayitlari ve yaygin DNS-over-HTTPS kacis sunuculari (`cloudflare-dns.com`, `dns.google`, `dns.quad9.net`, `dns.adguard-dns.com`, `dns.nextdns.io`, `doh.cleanbrowsing.org`, `doh.dns.sb`, `freedns.controld.com`) birlikte engellenir. +4. **Sifir Harici Bagimlilikli Win32 / POSIX Proses Denetleyicisi:** + * Windows'ta `psutil` gerektirmeden dogrudan `ctypes` uzerinden Win32 `CreateToolhelp32Snapshot` (`Process32FirstW` / `Process32NextW`) kullanilir. Kritik sistem surecleri (`explorer.exe`, `svchost.exe`, `lsass.exe`, `csrss.exe`, `python.exe`, `focusflow.exe`, `wt.exe`) koruma listesiyle kesin olarak engellenir. +5. **Gercek Telemetri ve Yuksek Surtunmeli Siki Mod (Friction Challenge):** + * Tum istatistikler, aktif gun serisi ve tamamlanma oranlari dogrudan `sessions.json` verilerinden hesaplanir. Siki mod aktifken kopyala-yapistir kapali 16 karakterlik dogrulama kodu olmadan oturum veya pencere erken kapatilamaz. --- -## 💻 Kullanım Kılavuzu +## Hizli Baslangic -> **Not:** Windows hosts dosyasını yönetebilmek için terminali **Yönetici Olarak (Administrator)** çalıştırın. +### 1. Masaustu HUD (GUI) +Windows uzerinde `Launch_FocusFlow_GUI.bat` dosyasini calistirin veya terminalden baslatin: +```bash +python FocusFlowGUI.py +``` +Yonetici (Administrator) yetkisiyle baslatmak icin: +```bash +python FocusFlowGUI.py --elevate +``` + +### 2. Komut Satiri Araci (Go CLI) +Kaynak koddan derleme: +```bash +CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.Version=2.1.0" -o focusflow.exe ./cmd/focusflow +``` +Temel komutlar: ```bash -# 50 dakikalık yazılımcı seansı başlat -focusflow start --profile dev --minutes 50 +# 50 dakikalik yazilimci seansi (Yonetici yetkisi isteyerek) +focusflow start --profile dev --minutes 50 --elevate -# 25 dakikalık YKS / KPSS çalışma seansı başlat +# 25 dakikalik akademik/sinav calisma seansi focusflow start --profile study --minutes 25 -# Korumayı anında kaldır ve hosts dosyasını sıfırla -focusflow stop +# Hardcore Aegis kilidi (Anti-Cheat aktif) +focusflow start --profile hardcore --strict hardcore -# Durumu kontrol et +# Kalkan, yetki ve journal durumunu incele focusflow status +focusflow status --json + +# Ozel site ve uygulama kurallarini yonet +focusflow list --json +focusflow add site reddit.com +focusflow add app steam.exe + +# Gercek calisma istatistikleri ve 7 gunluk ASCII grafik +focusflow stats --days 7 +focusflow export --format csv --out rapor.csv -# Geçmiş çalışma istatistiklerini gör -focusflow stats +# Sistem tanilama ve cokme sonrasi kurtarma +focusflow doctor +focusflow recover --elevate + +# Aninda geri alma ve DNS onbellek temizligi +focusflow stop +focusflow flush +``` + +--- + +## Testler + +Tum Go ve Python testleri gecici `FOCUSFLOW_HOME` dizinlerinde izole olarak calisir; gercek `%APPDATA%` verilerinize veya sistem `hosts` dosyaniza dokunmaz: + +```bash +go vet ./... +go test -v ./... +python -m pytest -v ``` --- -## 📄 Lisans +## Lisans -Bu proje [MIT Lisansı](LICENSE) ile tamamen açık kaynaklıdır. -Geliştirici: [aloneangel45](https://github.com/aloneangel45) +Bu proje [MIT Lisansi](LICENSE) kapsaminda acik kaynaklidir. +Gelistirici: [aloneangel45](https://github.com/aloneangel45) diff --git a/SECURITY.md b/SECURITY.md index a580e20..e6f1f76 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,14 +1,21 @@ -# Güvenlik Politikası +# Security Policy -## Desteklenen Sürümler +## Supported Versions -| Sürüm | Destekleniyor mu? | -| ----- | ------------------ | -| 1.0.x | :white_check_mark: | -| < 1.0 | :x: | +| Version | Status | +| :------ | :------------------- | +| 2.1.x | Supported | +| 2.0.x | Critical fixes only | +| < 2.0 | Unsupported | -## Güvenlik Açığı Bildirimi +## Security Architecture Notes -FocusFlow sistem düzeyinde proses ve DNS/hosts filtrelemesi yaptığı için güvenlik bizim için kritik öneme sahiptir. -Bir güvenlik açığı tespit ettiğinizde lütfen genel Issue açmak yerine `security@aloneangel.dev` adresine bildiriniz veya GitHub Security Advisory oluşturunuz. -Bildirilen açıklar en geç 48 saat içinde değerlendirmeye alınacaktır. +FocusFlow operates at the operating-system boundary by managing DNS sinkhole blocks in the system `hosts` file and terminating user-configured distraction executables: + +- **Strict RFC-1123 Domain Validation:** Rejects control characters, embedded newlines/whitespace, IPv4/IPv6 literals, `localhost`, `localdomain`, and `*.local` domains to prevent `hosts` injection. +- **Protected System Binary Denylist:** Prevents adding or terminating PIDs `0`, `4`, current/parent PIDs, and critical OS/host binaries (`csrss.exe`, `smss.exe`, `lsass.exe`, `services.exe`, `svchost.exe`, `wininit.exe`, `winlogon.exe`, `dwm.exe`, `explorer.exe`, `sihost.exe`, `fontdrvhost.exe`, `focusflow.exe`, `python.exe`, `pythonw.exe`, `conhost.exe`, `wt.exe`). +- **ACL-Preserving Crash Recovery:** Uses Win32 `ReplaceFileW` and POSIX mode preservation alongside a SHA-256 write-ahead rollback journal (`hosts.focusflow.journal.json`) so network resolution permissions are never degraded. + +## Reporting a Vulnerability + +Please do **not** open a public GitHub issue for security vulnerabilities. Report suspected vulnerabilities privately via `security@aloneangel.dev` or through a GitHub Security Advisory on this repository. Reports are triaged within 48 hours. diff --git a/cmd/focusflow/main.go b/cmd/focusflow/main.go index 5e2e921..87ad544 100644 --- a/cmd/focusflow/main.go +++ b/cmd/focusflow/main.go @@ -2,11 +2,15 @@ package main import ( "bufio" + "encoding/json" "flag" "fmt" + "io" "os" "os/signal" + "path/filepath" "runtime" + "sort" "strings" "syscall" "time" @@ -17,288 +21,426 @@ import ( "github.com/aloneangel45/focusflow/pkg/tui" ) -const Version = "2.0.0" +// Version is set at build time via -ldflags "-X main.Version=..." +var Version = "2.1.0" func main() { - if len(os.Args) < 2 { - handleInteractiveMenu() - return + os.Exit(runCLI(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) +} + +func stripElevateFlag(args []string) ([]string, bool) { + cleaned := make([]string, 0, len(args)) + elevate := false + for _, a := range args { + if a == "--elevate" || a == "-elevate" { + elevate = true + continue + } + cleaned = append(cleaned, a) } + return cleaned, elevate +} + +func runStartupAutoRecovery() (*engine.RecoveryResult, error) { + hosts := engine.NewHostsManager() + return hosts.RecoverIfOrphaned(func(sessionID string) { + if store, err := storage.NewStore(); err == nil { + _, _ = store.MarkOrphanedSession(sessionID, time.Now().UTC()) + } + }) +} - command := strings.ToLower(os.Args[1]) +func runCLI(rawArgs []string, stdin io.Reader, stdout, stderr io.Writer) int { + args, wantElevate := stripElevateFlag(rawArgs) + if wantElevate && !engine.IsElevated() { + if err := engine.ElevateSelf(args); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Elevation failed: %v\n", err) + return 1 + } + _, _ = fmt.Fprintln(stdout, "[OK] Launched elevated FocusFlow process.") + return 0 + } + + if len(args) == 0 { + _, _ = runStartupAutoRecovery() + return handleInteractiveMenu(stdin, stdout, stderr) + } + + command := strings.ToLower(strings.TrimSpace(args[0])) + subArgs := args[1:] + + // Run automatic orphan journal recovery before regular commands + if command != "version" && command != "--version" && command != "-v" && + command != "help" && command != "--help" && command != "-h" && + command != "doctor" && command != "recover" { + _, _ = runStartupAutoRecovery() + } switch command { case "start": - handleStart(os.Args[2:]) + return handleStart(subArgs, stdout, stderr) case "stop": - handleStop() + return handleStop(stdout, stderr) case "status": - handleStatus() + return handleStatus(subArgs, stdout, stderr) case "flush": - handleFlush() + return handleFlush(stdout, stderr) case "stats": - handleStats() + return handleStats(subArgs, stdout, stderr) + case "export": + return handleExport(subArgs, stdout, stderr) + case "doctor": + return handleDoctor(subArgs, stdout, stderr) + case "recover": + return handleRecover(subArgs, stdout, stderr) case "menu": - handleInteractiveMenu() + return handleInteractiveMenu(stdin, stdout, stderr) case "list": - handleListConfig() + return handleListConfig(subArgs, stdout, stderr) case "add": - handleAdd(os.Args[2:]) + return handleAdd(subArgs, stdout, stderr) case "remove", "rm": - handleRemove(os.Args[2:]) + return handleRemove(subArgs, stdout, stderr) case "version", "--version", "-v": - fmt.Printf("FocusFlow v%s (%s/%s)\n", Version, runtime.GOOS, runtime.GOARCH) + _, _ = fmt.Fprintf(stdout, "FocusFlow v%s (%s/%s)\n", Version, runtime.GOOS, runtime.GOARCH) + return 0 + case "help", "--help", "-h": + tui.PrintBannerTo(stdout, Version) + printUsage(stdout) + return 0 default: - tui.PrintBanner() - fmt.Printf("Unknown command: %s\n\n", command) - printUsage() + tui.PrintBannerTo(stdout, Version) + _, _ = fmt.Fprintf(stderr, "[ERR] Unknown command: %s\n\n", command) + printUsage(stdout) + return 1 } } -func printUsage() { - fmt.Println("Usage: focusflow [options]") - fmt.Println("\nAvailable Commands:") - fmt.Println(" menu Launch interactive configuration & session menu") - fmt.Println(" start Start a deep work sprint with atomic blocking active") - fmt.Println(" stop Rollback hosts file and restore unrestricted system access") - fmt.Println(" status Inspect whether FocusFlow active blocklist is currently engaged") - fmt.Println(" list List all active profiles, custom blocked sites & apps") - fmt.Println(" add site Add custom domain to blocklist") - fmt.Println(" add app Add custom process to blocklist") - fmt.Println(" remove site Remove custom domain from blocklist") - fmt.Println(" remove app Remove custom process from blocklist") - fmt.Println(" flush Purge local DNS resolver cache immediately") - fmt.Println(" stats Display lifetime focus session metrics and streak summary") - fmt.Println(" version Print application version") - fmt.Println("\nStart Options:") - fmt.Println(" --profile Profile to activate: dev, study, hardcore (default: study)") - fmt.Println(" --minutes Duration in minutes (default: profile default)") - fmt.Println(" --strict Strictness level: relaxed, standard, hardcore (default: standard)") +func printUsage(w io.Writer) { + _, _ = fmt.Fprintln(w, "Usage: focusflow [--elevate] [options]") + _, _ = fmt.Fprintln(w, "\nAvailable Commands:") + _, _ = fmt.Fprintln(w, " menu Launch interactive configuration & session dashboard") + _, _ = fmt.Fprintln(w, " start Start a deep work sprint with crash-safe blocking") + _, _ = fmt.Fprintln(w, " stop Rollback hosts file and restore unrestricted access") + _, _ = fmt.Fprintln(w, " status [--json] Inspect shield state, privileges, and active journal") + _, _ = fmt.Fprintln(w, " list [--json] List all active profiles, custom blocked sites & apps") + _, _ = fmt.Fprintln(w, " add site Add validated RFC-1123 custom domain to blocklist") + _, _ = fmt.Fprintln(w, " add app Add custom process to blocklist (denylist protected)") + _, _ = fmt.Fprintln(w, " remove site Remove custom domain from blocklist") + _, _ = fmt.Fprintln(w, " remove app Remove custom process from blocklist") + _, _ = fmt.Fprintln(w, " stats [--days 7] [--json] Display focus metrics, streak, completion rate & chart") + _, _ = fmt.Fprintln(w, " export [--format json|csv] Export session telemetry (--out )") + _, _ = fmt.Fprintln(w, " doctor [--json] Audit privileges, hosts integrity, and journal health") + _, _ = fmt.Fprintln(w, " recover [--force] [--json] Recover orphaned crash/reboot hosts state") + _, _ = fmt.Fprintln(w, " flush Purge local DNS resolver cache immediately") + _, _ = fmt.Fprintln(w, " version Print application version") + _, _ = fmt.Fprintln(w, "\nGlobal / Start Options:") + _, _ = fmt.Fprintln(w, " --elevate Request Administrator/sudo privilege elevation") + _, _ = fmt.Fprintln(w, " --profile Profile: study, dev, hardcore (default: study)") + _, _ = fmt.Fprintln(w, " --minutes Duration in minutes (default: profile default)") + _, _ = fmt.Fprintln(w, " --strict Strictness: relaxed, standard, hardcore (default: standard)") } -func handleInteractiveMenu() { - tui.PrintBanner() - reader := bufio.NewReader(os.Stdin) +func shieldModeString(elevated bool) string { + if elevated { + return "FULL SHIELD [HOSTS + PROC]" + } + return "PROCESS-ONLY [UNPRIVILEGED]" +} + +func handleInteractiveMenu(stdin io.Reader, stdout, stderr io.Writer) int { + tui.PrintBannerTo(stdout, Version) + reader := bufio.NewReader(stdin) for { - fmt.Println(" [ FOCUSFLOW INTERACTIVE DASHBOARD ]") - fmt.Println(" 1. ▶ Start Sprint (Study Mode - 25 min)") - fmt.Println(" 2. ▶ Start Sprint (Dev Mode - 50 min)") - fmt.Println(" 3. ▶ Start Sprint (Hardcore Aegis Lockdown)") - fmt.Println(" 4. 📋 List Blocked Sites & Applications") - fmt.Println(" 5. ➕ Add Custom Blocked Website (e.g. twitter.com)") - fmt.Println(" 6. ➕ Add Custom Blocked Application (e.g. discord.exe)") - fmt.Println(" 7. ➖ Remove Custom Blocked Item") - fmt.Println(" 8. 🛑 Emergency Stop / Rollback All Blocks") - fmt.Println(" 9. 📊 View Lifetime Productivity Statistics") - fmt.Println(" 0. 🚪 Exit") - fmt.Print("\n Select an option [0-9]: ") - - input, _ := reader.ReadString('\n') + elevated := engine.IsElevated() + _, _ = fmt.Fprintf(stdout, " [ FOCUSFLOW INTERACTIVE DASHBOARD | %s ]\n", shieldModeString(elevated)) + _, _ = fmt.Fprintln(stdout, " 1. [START] Sprint (Study Mode - 25 min)") + _, _ = fmt.Fprintln(stdout, " 2. [START] Sprint (Dev Mode - 50 min)") + _, _ = fmt.Fprintln(stdout, " 3. [START] Sprint (Hardcore Aegis Lockdown)") + _, _ = fmt.Fprintln(stdout, " 4. [LIST] Blocked Sites & Applications") + _, _ = fmt.Fprintln(stdout, " 5. [ADD] Custom Blocked Website (e.g. twitter.com)") + _, _ = fmt.Fprintln(stdout, " 6. [ADD] Custom Blocked Application (e.g. discord.exe)") + _, _ = fmt.Fprintln(stdout, " 7. [REM] Remove Custom Blocked Item") + _, _ = fmt.Fprintln(stdout, " 8. [STOP] Emergency Stop / Rollback All Blocks") + _, _ = fmt.Fprintln(stdout, " 9. [STATS] View Productivity Analytics & 7-Day Chart") + _, _ = fmt.Fprintln(stdout, " 0. [EXIT] Quit") + _, _ = fmt.Fprint(stdout, "\n Select an option [0-9]: ") + + input, err := reader.ReadString('\n') + if err != nil && len(input) == 0 { + return 0 + } choice := strings.TrimSpace(input) switch choice { case "1": - handleStart([]string{"--profile", "study", "--minutes", "25"}) - return + return handleStart([]string{"--profile", "study", "--minutes", "25"}, stdout, stderr) case "2": - handleStart([]string{"--profile", "dev", "--minutes", "50"}) - return + return handleStart([]string{"--profile", "dev", "--minutes", "50"}, stdout, stderr) case "3": - handleStart([]string{"--profile", "hardcore", "--strict", "hardcore"}) - return + return handleStart([]string{"--profile", "hardcore", "--strict", "hardcore"}, stdout, stderr) case "4": - handleListConfig() + _ = handleListConfig(nil, stdout, stderr) case "5": - fmt.Print(" Enter domain to block (e.g. reddit.com): ") + _, _ = fmt.Fprint(stdout, " Enter domain to block (e.g. reddit.com): ") domain, _ := reader.ReadString('\n') domain = strings.TrimSpace(domain) if domain != "" { - handleAdd([]string{"site", domain}) + _ = handleAdd([]string{"site", domain}, stdout, stderr) } case "6": - fmt.Print(" Enter application executable name (e.g. steam.exe): ") + _, _ = fmt.Fprint(stdout, " Enter application executable name (e.g. steam.exe): ") app, _ := reader.ReadString('\n') app = strings.TrimSpace(app) if app != "" { - handleAdd([]string{"app", app}) + _ = handleAdd([]string{"app", app}, stdout, stderr) } case "7": - fmt.Print(" Enter type to remove ('site' or 'app'): ") + _, _ = fmt.Fprint(stdout, " Enter type to remove ('site' or 'app'): ") itemType, _ := reader.ReadString('\n') itemType = strings.TrimSpace(itemType) - fmt.Print(" Enter name to remove: ") + _, _ = fmt.Fprint(stdout, " Enter name to remove: ") name, _ := reader.ReadString('\n') name = strings.TrimSpace(name) if itemType != "" && name != "" { - handleRemove([]string{itemType, name}) + _ = handleRemove([]string{itemType, name}, stdout, stderr) } case "8": - handleStop() + _ = handleStop(stdout, stderr) case "9": - handleStats() + _ = handleStats(nil, stdout, stderr) case "0", "exit", "q": - fmt.Println(" Goodbye! Stay focused.") - return + _, _ = fmt.Fprintln(stdout, " [OK] Session closed.") + return 0 default: - fmt.Println(" Invalid option. Please enter 0-9.") + _, _ = fmt.Fprintln(stdout, " [WARN] Invalid option. Enter 0-9.") } - fmt.Println("\n" + strings.Repeat("─", 60) + "\n") + _, _ = fmt.Fprintln(stdout, "\n"+strings.Repeat("─", 68)+"\n") } } -func handleListConfig() { +type listJSONOutput struct { + ConfigPath string `json:"config_path"` + StateDir string `json:"state_dir"` + CustomDomains []string `json:"custom_domains"` + CustomProcesses []string `json:"custom_processes"` + Profiles map[string]*profile.FocusProfile `json:"profiles"` +} + +func handleListConfig(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("list", flag.ContinueOnError) + fs.SetOutput(stderr) + asJSON := fs.Bool("json", false, "Output configuration as JSON") + if err := fs.Parse(args); err != nil { + return 1 + } + cfg, err := profile.LoadConfig() if err != nil { - fmt.Printf("Error reading config: %v\n", err) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Error reading config: %v\n", err) + return 1 + } + + if *asJSON { + out := listJSONOutput{ + ConfigPath: profile.GetConfigPath(), + StateDir: profile.GetConfigDir(), + CustomDomains: cfg.CustomDomains, + CustomProcesses: cfg.CustomProcesses, + Profiles: cfg.Profiles, + } + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(out) + return 0 } - fmt.Println("\n=== FocusFlow Custom User Rules ===") - fmt.Printf("Config File: %s\n\n", profile.GetConfigPath()) + _, _ = fmt.Fprintln(stdout, "\n=== FocusFlow Configuration & Rules ===") + _, _ = fmt.Fprintf(stdout, "State Dir: %s\n", profile.GetConfigDir()) + _, _ = fmt.Fprintf(stdout, "Config File: %s\n\n", profile.GetConfigPath()) - fmt.Println("Custom Blocked Domains:") + _, _ = fmt.Fprintln(stdout, "Custom Blocked Domains:") if len(cfg.CustomDomains) == 0 { - fmt.Println(" (None. Use 'focusflow add site ' to add)") + _, _ = fmt.Fprintln(stdout, " (None. Use 'focusflow add site ' to add)") } else { for _, d := range cfg.CustomDomains { - fmt.Printf(" • %s\n", d) + _, _ = fmt.Fprintf(stdout, " - %s\n", d) } } - fmt.Println("\nCustom Blocked Applications:") + _, _ = fmt.Fprintln(stdout, "\nCustom Blocked Applications:") if len(cfg.CustomProcesses) == 0 { - fmt.Println(" (None. Use 'focusflow add app ' to add)") + _, _ = fmt.Fprintln(stdout, " (None. Use 'focusflow add app ' to add)") } else { for _, p := range cfg.CustomProcesses { - fmt.Printf(" • %s\n", p) + _, _ = fmt.Fprintf(stdout, " - %s\n", p) } } - fmt.Println("\nStandard Profiles Available:") - for name, p := range cfg.Profiles { - fmt.Printf(" • [%s] %s (%d mins work / %d mins break)\n", + _, _ = fmt.Fprintln(stdout, "\nProfiles Available:") + names := make([]string, 0, len(cfg.Profiles)) + for name := range cfg.Profiles { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + p := cfg.Profiles[name] + _, _ = fmt.Fprintf(stdout, " - [%s] %s (%d min work / %d min break)\n", name, p.Description, p.DefaultWorkMinutes, p.DefaultBreakMinutes) } - fmt.Println() + _, _ = fmt.Fprintln(stdout) + return 0 } -func handleAdd(args []string) { +func handleAdd(args []string, stdout, stderr io.Writer) int { if len(args) < 2 { - fmt.Println("Usage: focusflow add site OR focusflow add app ") - return + _, _ = fmt.Fprintln(stderr, "Usage: focusflow add site OR focusflow add app ") + return 1 } - itemType := strings.ToLower(args[0]) - itemValue := strings.ToLower(strings.TrimSpace(args[1])) + itemType := strings.ToLower(strings.TrimSpace(args[0])) + rawValue := args[1] cfg, err := profile.LoadConfig() if err != nil { - fmt.Printf("Error loading config: %v\n", err) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Error loading config: %v\n", err) + return 1 } switch itemType { case "site", "domain", "web": + cleanDomain, err := engine.SanitizeDomain(rawValue) + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Invalid domain %q: %v\n", rawValue, err) + return 1 + } for _, d := range cfg.CustomDomains { - if d == itemValue { - fmt.Printf("Domain '%s' is already in custom blocklist.\n", itemValue) - return + if d == cleanDomain { + _, _ = fmt.Fprintf(stdout, "[INFO] Domain '%s' is already in custom blocklist.\n", cleanDomain) + return 0 } } - cfg.CustomDomains = append(cfg.CustomDomains, itemValue) + cfg.CustomDomains = append(cfg.CustomDomains, cleanDomain) if err := profile.SaveConfig(cfg); err != nil { - fmt.Printf("Error saving config: %v\n", err) - } else { - fmt.Printf("✔ Added '%s' to custom blocked websites.\n", itemValue) + _, _ = fmt.Fprintf(stderr, "[ERR] Error saving config: %v\n", err) + return 1 } + _, _ = fmt.Fprintf(stdout, "[OK] Added '%s' to custom blocked websites.\n", cleanDomain) + return 0 + case "app", "proc", "process", "exe": - if !strings.HasSuffix(itemValue, ".exe") { - itemValue = itemValue + ".exe" + cleanProc, err := engine.NormalizeProcessName(rawValue) + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Cannot block process %q: %v\n", rawValue, err) + return 1 } for _, p := range cfg.CustomProcesses { - if p == itemValue { - fmt.Printf("Application '%s' is already in custom blocklist.\n", itemValue) - return + if p == cleanProc { + _, _ = fmt.Fprintf(stdout, "[INFO] Application '%s' is already in custom blocklist.\n", cleanProc) + return 0 } } - cfg.CustomProcesses = append(cfg.CustomProcesses, itemValue) + cfg.CustomProcesses = append(cfg.CustomProcesses, cleanProc) if err := profile.SaveConfig(cfg); err != nil { - fmt.Printf("Error saving config: %v\n", err) - } else { - fmt.Printf("✔ Added '%s' to custom blocked applications.\n", itemValue) + _, _ = fmt.Fprintf(stderr, "[ERR] Error saving config: %v\n", err) + return 1 } + _, _ = fmt.Fprintf(stdout, "[OK] Added '%s' to custom blocked applications.\n", cleanProc) + return 0 + default: - fmt.Println("Invalid item type. Use 'site' or 'app'.") + _, _ = fmt.Fprintln(stderr, "[ERR] Invalid item type. Use 'site' or 'app'.") + return 1 } } -func handleRemove(args []string) { +func handleRemove(args []string, stdout, stderr io.Writer) int { if len(args) < 2 { - fmt.Println("Usage: focusflow remove site OR focusflow remove app ") - return + _, _ = fmt.Fprintln(stderr, "Usage: focusflow remove site OR focusflow remove app ") + return 1 } - itemType := strings.ToLower(args[0]) - itemValue := strings.ToLower(strings.TrimSpace(args[1])) + itemType := strings.ToLower(strings.TrimSpace(args[0])) + rawValue := strings.TrimSpace(args[1]) cfg, err := profile.LoadConfig() if err != nil { - fmt.Printf("Error loading config: %v\n", err) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Error loading config: %v\n", err) + return 1 } switch itemType { case "site", "domain", "web": + target := strings.ToLower(rawValue) + if clean, err := engine.SanitizeDomain(rawValue); err == nil { + target = clean + } var updated []string found := false for _, d := range cfg.CustomDomains { - if d == itemValue { + if d == target { found = true } else { updated = append(updated, d) } } if !found { - fmt.Printf("Domain '%s' was not found in custom blocklist.\n", itemValue) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Domain '%s' was not found in custom blocklist.\n", target) + return 1 } cfg.CustomDomains = updated - _ = profile.SaveConfig(cfg) - fmt.Printf("✔ Removed '%s' from custom blocked websites.\n", itemValue) + if err := profile.SaveConfig(cfg); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Error saving config: %v\n", err) + return 1 + } + _, _ = fmt.Fprintf(stdout, "[OK] Removed '%s' from custom blocked websites.\n", target) + return 0 + case "app", "proc", "process", "exe": - if !strings.HasSuffix(itemValue, ".exe") { - itemValue = itemValue + ".exe" + target := strings.ToLower(rawValue) + if !strings.HasSuffix(target, ".exe") { + target += ".exe" } var updated []string found := false for _, p := range cfg.CustomProcesses { - if p == itemValue { + if p == target { found = true } else { updated = append(updated, p) } } if !found { - fmt.Printf("Application '%s' was not found in custom blocklist.\n", itemValue) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Application '%s' was not found in custom blocklist.\n", target) + return 1 } cfg.CustomProcesses = updated - _ = profile.SaveConfig(cfg) - fmt.Printf("✔ Removed '%s' from custom blocked applications.\n", itemValue) + if err := profile.SaveConfig(cfg); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Error saving config: %v\n", err) + return 1 + } + _, _ = fmt.Fprintf(stdout, "[OK] Removed '%s' from custom blocked applications.\n", target) + return 0 + default: - fmt.Println("Invalid item type. Use 'site' or 'app'.") + _, _ = fmt.Fprintln(stderr, "[ERR] Invalid item type. Use 'site' or 'app'.") + return 1 } } -func handleStart(args []string) { - fs := flag.NewFlagSet("start", flag.ExitOnError) +func handleStart(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("start", flag.ContinueOnError) + fs.SetOutput(stderr) profileName := fs.String("profile", "study", "Profile name") minutes := fs.Int("minutes", 0, "Duration in minutes") - strictness := fs.String("strict", "standard", "Strictness level") - _ = fs.Parse(args) + secondsOverride := fs.Int("seconds", 0, "Duration override in seconds (for rapid testing)") + strictness := fs.String("strict", "", "Strictness level: relaxed, standard, hardcore") + if err := fs.Parse(args); err != nil { + return 1 + } - tui.PrintBanner() + tui.PrintBannerTo(stdout, Version) prof := profile.LoadOrDefault(*profileName) durationMin := prof.DefaultWorkMinutes @@ -306,141 +448,483 @@ func handleStart(args []string) { durationMin = *minutes } totalSeconds := durationMin * 60 + if *secondsOverride > 0 { + totalSeconds = *secondsOverride + if durationMin <= 0 { + durationMin = 1 + } + } strictLevel := engine.StrictnessStandard - switch strings.ToLower(*strictness) { + if prof.Name == "hardcore" && *strictness == "" { + strictLevel = engine.StrictnessHardcore + } + switch strings.ToLower(strings.TrimSpace(*strictness)) { case "hardcore": strictLevel = engine.StrictnessHardcore case "relaxed": strictLevel = engine.StrictnessRelaxed + case "standard": + strictLevel = engine.StrictnessStandard } - fmt.Printf(" ▶ Starting %s session (%d minutes | Strictness: %s)\n", - prof.Name, durationMin, strictLevel) + startTime := time.Now().UTC() + expectedEnd := startTime.Add(time.Duration(totalSeconds) * time.Second) + sessionID := storage.GenerateSessionID() + + store, storeErr := storage.NewStore() + if storeErr == nil { + _ = store.StartSession(sessionID, prof.Name, durationMin, startTime) + } + + _, _ = fmt.Fprintf(stdout, " [ACTIVE] Starting '%s' sprint (%d min | Strictness: %s | Session: %s)\n", + prof.Name, durationMin, strictLevel, sessionID) hosts := engine.NewHostsManager() dns := &engine.DnsEngine{} procSup := engine.NewProcessSupervisor(prof.BlockedProcesses) antiCheat := engine.NewAntiCheatGuard(strictLevel) - // Step 1: Engage Hosts Blocklist - fmt.Print(" • Engaging atomic hosts blocklist... ") allDomains := append([]string{}, prof.BlockedDomains...) allDomains = append(allDomains, dns.GetDoHBypassDomains()...) - if err := hosts.ApplyBlocklist(allDomains); err != nil { - fmt.Printf("FAILED (%v)\n", err) - fmt.Println(" ⚠ Please run terminal as Administrator to modify system hosts.") - } else { - fmt.Println("OK (Backup secured with SHA-256)") + sessionMeta := engine.SessionMeta{ + SessionID: sessionID, + PID: os.Getpid(), + StartedAt: startTime, + ExpectedEndAt: expectedEnd, + Profile: prof.Name, } - // Step 2: Flush DNS resolver cache - fmt.Print(" • Purging DNS resolver cache (Anti-DoH)... ") - _ = dns.FlushResolverCache() - fmt.Println("OK") + hostsEngaged := false + _, _ = fmt.Fprint(stdout, " [INFO] Engaging dual-stack atomic hosts sinkhole... ") + if err := hosts.ApplyBlocklistWithSession(allDomains, sessionMeta); err != nil { + _, _ = fmt.Fprintf(stdout, "SKIPPED (%v)\n", err) + _, _ = fmt.Fprintln(stdout, " [WARN] Shield Mode: PROCESS-ONLY [UNPRIVILEGED] (re-run with --elevate for hosts sinkhole)") + } else { + hostsEngaged = true + _, _ = fmt.Fprintln(stdout, "[OK] FULL SHIELD [HOSTS + PROC] (SHA-256 journaled)") + _, _ = fmt.Fprint(stdout, " [INFO] Purging DNS resolver cache (Anti-DoH)... ") + _ = dns.FlushResolverCache() + _, _ = fmt.Fprintln(stdout, "[OK]") + } - // Setup graceful Ctrl+C interrupt handler sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) + defer signal.Stop(sigChan) - go func() { - <-sigChan - fmt.Println("\n\n ⚠ Interrupt signal received! Rolling back hosts...") - _ = hosts.Rollback() - _ = dns.FlushResolverCache() - fmt.Println(" ✔ System access cleanly restored. Exiting.") - os.Exit(0) - }() - - // Step 3: Run interactive loop - elapsedSeconds := 0 totalBlocked := 0 - ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() - for elapsedSeconds < totalSeconds { - <-ticker.C - elapsedSeconds++ + deadline := time.Now().Add(time.Duration(totalSeconds) * time.Second) + tickCount := 0 - // Process surveillance scan - terminatedProcs := procSup.ScanAndTerminate() - antiCheatProcs := antiCheat.Enforce() - - hits := len(terminatedProcs) + len(antiCheatProcs) - if hits > 0 { - totalBlocked += hits - for _, p := range append(terminatedProcs, antiCheatProcs...) { - fmt.Printf("\n ✘ Terminated distraction: %s\n", p) + for { + select { + case <-sigChan: + elapsed := int(time.Since(startTime).Seconds()) + if elapsed < 0 { + elapsed = 0 + } + _, _ = fmt.Fprintln(stdout, "\n\n [WARN] Interrupt signal received. Rolling back system state...") + if hostsEngaged { + _ = hosts.Rollback() + _ = dns.FlushResolverCache() + } + if store != nil { + _ = store.FinalizeSession(sessionID, prof.Name, elapsed/60, false, "aborted", totalBlocked, startTime, time.Now().UTC()) + } + _, _ = fmt.Fprintln(stdout, " [OK] Hosts cleanly restored; session recorded as aborted.") + return 130 + + case <-ticker.C: + tickCount++ + rem := time.Until(deadline) + elapsedSeconds := totalSeconds - int(rem.Seconds()) + if elapsedSeconds < 0 { + elapsedSeconds = 0 + } + if elapsedSeconds > totalSeconds { + elapsedSeconds = totalSeconds } - } - tui.RenderProgress(elapsedSeconds, totalSeconds, prof.Name, totalBlocked) - } + terminatedProcs := procSup.ScanAndTerminate() + antiCheatProcs := antiCheat.Enforce() - fmt.Println("\n\n 🎉 Sprint Complete! Take a well-deserved break.") + hits := len(terminatedProcs) + len(antiCheatProcs) + if hits > 0 { + totalBlocked += hits + for _, p := range append(terminatedProcs, antiCheatProcs...) { + _, _ = fmt.Fprintf(stdout, "\n [BLOCKED] Terminated distraction: %s\n", p) + } + } - // Clean rollback - _ = hosts.Rollback() - _ = dns.FlushResolverCache() + // Mid-session hosts tamper watchdog for standard and hardcore modes + if hostsEngaged && (strictLevel == engine.StrictnessStandard || strictLevel == engine.StrictnessHardcore) && tickCount%5 == 0 { + if tampered, err := hosts.VerifyOrReapply(allDomains, sessionMeta); err == nil && tampered { + totalBlocked++ + dns.FlushResolverCacheAsync() + _, _ = fmt.Fprintln(stdout, "\n [BLOCKED] Hosts tamper detected; sinkhole re-applied.") + } + } - // Record into storage - if store, err := storage.NewStore(); err == nil { - _ = store.RecordSession(prof.Name, durationMin, true, totalBlocked) + _, _ = fmt.Fprint(stdout, tui.FormatProgress(elapsedSeconds, totalSeconds, prof.Name, totalBlocked)) + + if rem <= 0 { + _, _ = fmt.Fprintln(stdout, "\n\n [OK] Sprint complete.") + if hostsEngaged { + _ = hosts.Rollback() + _ = dns.FlushResolverCache() + } + if store != nil { + _ = store.FinalizeSession(sessionID, prof.Name, durationMin, true, "completed", totalBlocked, startTime, time.Now().UTC()) + } + _, _ = fmt.Fprintln(stdout, " [OK] All system protections rolled back cleanly.") + return 0 + } + } } - - fmt.Println(" ✔ All system protections rolled back cleanly.") } -func handleStop() { - fmt.Println(" • Rolling back hosts file and flushing DNS...") +func handleStop(stdout, stderr io.Writer) int { + _, _ = fmt.Fprintln(stdout, " [INFO] Rolling back hosts file and flushing DNS...") hosts := engine.NewHostsManager() dns := &engine.DnsEngine{} + var journalSessionID string + if j, err := hosts.LoadJournal(); err == nil && j != nil { + journalSessionID = j.SessionID + } + if err := hosts.Rollback(); err != nil { - fmt.Printf(" ✘ Rollback failed: %v\n", err) - } else { - _ = dns.FlushResolverCache() - fmt.Println(" ✔ Clean rollback complete. Unrestricted access restored.") + _, _ = fmt.Fprintf(stderr, " [ERR] Rollback failed: %v (re-run with --elevate if permission denied)\n", err) + return 1 } + + if journalSessionID != "" { + if store, err := storage.NewStore(); err == nil { + _, _ = store.MarkOrphanedSession(journalSessionID, time.Now().UTC()) + } + } + + _ = dns.FlushResolverCache() + _, _ = fmt.Fprintln(stdout, " [OK] Clean rollback complete. Unrestricted access restored.") + return 0 +} + +type statusJSONOutput struct { + Version string `json:"version"` + Active bool `json:"active"` + Elevated bool `json:"elevated"` + ShieldMode string `json:"shield_mode"` + HostsPath string `json:"hosts_path"` + StateDir string `json:"state_dir"` + Journal *engine.HostsJournal `json:"journal,omitempty"` } -func handleStatus() { +func handleStatus(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("status", flag.ContinueOnError) + fs.SetOutput(stderr) + asJSON := fs.Bool("json", false, "Output status as JSON") + if err := fs.Parse(args); err != nil { + return 1 + } + hosts := engine.NewHostsManager() - if hosts.IsActive() { - fmt.Println(" • FocusFlow guard is currently ACTIVE (Lockdown Engaged).") + active := hosts.IsActive() + elevated := engine.IsElevated() + journal, _ := hosts.LoadJournal() + + if *asJSON { + out := statusJSONOutput{ + Version: Version, + Active: active, + Elevated: elevated, + ShieldMode: shieldModeString(elevated), + HostsPath: hosts.HostsPath(), + StateDir: storage.GetStateDir(), + Journal: journal, + } + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(out) + return 0 + } + + if active { + _, _ = fmt.Fprintf(stdout, " [ACTIVE] FocusFlow sinkhole is ENGAGED | %s\n", shieldModeString(elevated)) + if journal != nil { + _, _ = fmt.Fprintf(stdout, " Profile: %s | Session: %s | Owner PID: %d | Ends: %s\n", + journal.Profile, journal.SessionID, journal.PID, journal.ExpectedEndAt) + } } else { - fmt.Println(" • FocusFlow guard is INACTIVE (Unrestricted).") + _, _ = fmt.Fprintf(stdout, " [INACTIVE] FocusFlow guard is STANDBY | %s\n", shieldModeString(elevated)) } + return 0 } -func handleFlush() { - fmt.Print(" • Purging DNS resolver cache... ") +func handleFlush(stdout, stderr io.Writer) int { + _, _ = fmt.Fprint(stdout, " [INFO] Purging DNS resolver cache... ") dns := &engine.DnsEngine{} if err := dns.FlushResolverCache(); err != nil { - fmt.Printf("FAILED (%v)\n", err) - } else { - fmt.Println("OK") + _, _ = fmt.Fprintf(stderr, "[ERR] FAILED (%v)\n", err) + return 1 } + _, _ = fmt.Fprintln(stdout, "[OK]") + return 0 } -func handleStats() { - fmt.Println(" 📊 FocusFlow Historical Metrics:") +func handleStats(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("stats", flag.ContinueOnError) + fs.SetOutput(stderr) + days := fs.Int("days", 7, "Number of days for historical bar chart") + asJSON := fs.Bool("json", false, "Output statistics as JSON") + if err := fs.Parse(args); err != nil { + return 1 + } + store, err := storage.NewStore() if err != nil { - fmt.Printf(" ✘ Could not access metrics store: %v\n", err) - return + _, _ = fmt.Fprintf(stderr, "[ERR] Could not access metrics store: %v\n", err) + return 1 + } + + summary, err := store.ComputeAnalytics(*days, time.Now()) + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Could not compute stats: %v\n", err) + return 1 + } + + if *asJSON { + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(summary) + return 0 + } + + _, _ = fmt.Fprintln(stdout, " [STATS] FocusFlow Historical Telemetry") + _, _ = fmt.Fprintf(stdout, " - Completed Sprints: %d / %d (%.1f%% completion)\n", + summary.CompletedSprints, summary.AttemptedSprints, summary.CompletionRate) + _, _ = fmt.Fprintf(stdout, " - Deep Work Total: %.1f hrs (%d min)\n", + summary.TotalHours, summary.TotalMinutes) + _, _ = fmt.Fprintf(stdout, " - Active Streak: %d days\n", summary.ActiveStreakDays) + _, _ = fmt.Fprintf(stdout, " - Distractions Killed: %d\n\n", summary.TotalBlocked) + _, _ = fmt.Fprintf(stdout, " Last %d Days Focus Chart:\n", len(summary.Daily)) + _, _ = fmt.Fprint(stdout, tui.FormatDailyChart(summary.Daily)) + return 0 +} + +func handleExport(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("export", flag.ContinueOnError) + fs.SetOutput(stderr) + format := fs.String("format", "json", "Export format: json or csv") + outPath := fs.String("out", "", "Output file path (defaults to stdout)") + days := fs.Int("days", 7, "Summary window in days for JSON export") + if err := fs.Parse(args); err != nil { + return 1 + } + + store, err := storage.NewStore() + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Could not open session store: %v\n", err) + return 1 + } + + var dest io.Writer = stdout + var outFile *os.File + if strings.TrimSpace(*outPath) != "" { + cleanOut := filepath.Clean(*outPath) + if err := os.MkdirAll(filepath.Dir(cleanOut), 0755); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Cannot create export directory: %v\n", err) + return 1 + } + outFile, err = os.Create(cleanOut) + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Cannot create export file: %v\n", err) + return 1 + } + defer outFile.Close() + dest = outFile + } + + switch strings.ToLower(strings.TrimSpace(*format)) { + case "json": + if err := store.ExportJSON(dest, *days, time.Now()); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] JSON export failed: %v\n", err) + return 1 + } + case "csv": + if err := store.ExportCSV(dest); err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] CSV export failed: %v\n", err) + return 1 + } + default: + _, _ = fmt.Fprintf(stderr, "[ERR] Unsupported format %q (expected 'json' or 'csv')\n", *format) + return 1 + } + + if outFile != nil { + _, _ = fmt.Fprintf(stdout, "[OK] Exported %s report to %s\n", strings.ToUpper(*format), outFile.Name()) } + return 0 +} - sessions, minutes, blocked, err := store.GetTotalStats() +type doctorReport struct { + Version string `json:"version"` + OS string `json:"os"` + Arch string `json:"arch"` + Elevated bool `json:"elevated"` + ShieldMode string `json:"shield_mode"` + StateDir string `json:"state_dir"` + ConfigPath string `json:"config_path"` + SessionsPath string `json:"sessions_path"` + HostsPath string `json:"hosts_path"` + HostsReadable bool `json:"hosts_readable"` + HostsWritable bool `json:"hosts_writable"` + HostsActive bool `json:"hosts_active"` + JournalPresent bool `json:"journal_present"` + Recovery *engine.RecoveryResult `json:"recovery,omitempty"` + Healthy bool `json:"healthy"` +} + +func checkHostsWritable(path string) bool { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0644) if err != nil { - fmt.Printf(" ✘ Could not read stats: %v\n", err) - return + return false + } + _ = f.Close() + return true +} + +func handleDoctor(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("doctor", flag.ContinueOnError) + fs.SetOutput(stderr) + asJSON := fs.Bool("json", false, "Output diagnostic report as JSON") + if err := fs.Parse(args); err != nil { + return 1 + } + + hosts := engine.NewHostsManager() + recRes, recErr := runStartupAutoRecovery() + + _, readErr := os.ReadFile(hosts.HostsPath()) + readable := readErr == nil + writable := checkHostsWritable(hosts.HostsPath()) + elevated := engine.IsElevated() + _, jErr := hosts.LoadJournal() + + storePath := filepath.Join(storage.GetStateDir(), "sessions.json") + report := doctorReport{ + Version: Version, + OS: runtime.GOOS, + Arch: runtime.GOARCH, + Elevated: elevated, + ShieldMode: shieldModeString(elevated), + StateDir: storage.GetStateDir(), + ConfigPath: profile.GetConfigPath(), + SessionsPath: storePath, + HostsPath: hosts.HostsPath(), + HostsReadable: readable, + HostsWritable: writable, + HostsActive: hosts.IsActive(), + JournalPresent: jErr == nil, + Recovery: recRes, + Healthy: readable && recErr == nil, + } + + if *asJSON { + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(report) + if !report.Healthy { + return 1 + } + return 0 + } + + _, _ = fmt.Fprintln(stdout, "=== FocusFlow System Doctor ===") + _, _ = fmt.Fprintf(stdout, " Version: v%s (%s/%s)\n", report.Version, report.OS, report.Arch) + _, _ = fmt.Fprintf(stdout, " Shield Mode: %s\n", report.ShieldMode) + _, _ = fmt.Fprintf(stdout, " State Dir: %s\n", report.StateDir) + _, _ = fmt.Fprintf(stdout, " Hosts Path: %s (readable=%v, writable=%v)\n", + report.HostsPath, report.HostsReadable, report.HostsWritable) + _, _ = fmt.Fprintf(stdout, " Hosts Engaged: %v\n", report.HostsActive) + if recRes != nil && recRes.Recovered { + _, _ = fmt.Fprintf(stdout, " Orphan Recovery:[OK] Restored clean hosts (reason=%s, fallback=%v)\n", + recRes.Reason, recRes.UsedFallback) + } else if recErr != nil { + _, _ = fmt.Fprintf(stderr, " Orphan Recovery:[ERR] %v (re-run 'focusflow recover --elevate')\n", recErr) + return 1 + } else { + _, _ = fmt.Fprintf(stdout, " Journal State: [OK] (%s)\n", recRes.Reason) + } + return 0 +} + +func handleRecover(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("recover", flag.ContinueOnError) + fs.SetOutput(stderr) + force := fs.Bool("force", false, "Force rollback even if owning PID appears alive") + asJSON := fs.Bool("json", false, "Output recovery result as JSON") + if err := fs.Parse(args); err != nil { + return 1 } - hours := float64(minutes) / 60.0 - fmt.Printf(" • Total Completed Sprints: %d\n", sessions) - fmt.Printf(" • Total Deep Work Hours: %.1f hrs\n", hours) - fmt.Printf(" • Distractions Blocked: %d\n", blocked) + hosts := engine.NewHostsManager() + if *force { + var orphanID string + if j, err := hosts.LoadJournal(); err == nil && j != nil { + orphanID = j.SessionID + } + if err := hosts.Rollback(); err != nil { + if *asJSON { + _ = json.NewEncoder(stdout).Encode(map[string]any{"recovered": false, "error": err.Error()}) + } else { + _, _ = fmt.Fprintf(stderr, "[ERR] Force recovery failed: %v\n", err) + } + return 1 + } + if store, err := storage.NewStore(); err == nil { + _, _ = store.MarkOrphanedSession(orphanID, time.Now().UTC()) + } + dns := &engine.DnsEngine{} + dns.FlushResolverCacheAsync() + res := &engine.RecoveryResult{ + Recovered: true, + OrphanSessionID: orphanID, + Reason: "forced_rollback", + } + if *asJSON { + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(res) + } else { + _, _ = fmt.Fprintln(stdout, "[OK] Forced hosts recovery completed.") + } + return 0 + } + + res, err := runStartupAutoRecovery() + if *asJSON { + enc := json.NewEncoder(stdout) + enc.SetIndent("", " ") + _ = enc.Encode(res) + if err != nil { + return 1 + } + return 0 + } + + if err != nil { + _, _ = fmt.Fprintf(stderr, "[ERR] Orphan recovery failed: %v (try 'focusflow recover --elevate')\n", err) + return 1 + } + if res.Recovered { + _, _ = fmt.Fprintf(stdout, "[OK] Recovered orphaned hosts state (reason=%s, fallback=%v)\n", + res.Reason, res.UsedFallback) + } else { + _, _ = fmt.Fprintf(stdout, "[OK] No orphaned hosts state detected (%s)\n", res.Reason) + } + return 0 } diff --git a/focusflow_core/__init__.py b/focusflow_core/__init__.py new file mode 100644 index 0000000..71c3b79 --- /dev/null +++ b/focusflow_core/__init__.py @@ -0,0 +1,126 @@ +"""FocusFlow v2.1.0 unified standard-library core engine.""" + +__version__ = "2.1.0" + +from .paths import ( + get_backup_path, + get_config_path, + get_default_hosts_path, + get_gui_settings_path, + get_journal_path, + get_sessions_path, + get_state_dir, +) +from .sanitize import ( + DOH_BYPASS_DOMAINS, + PROTECTED_PROCESS_NAMES, + DomainValidationError, + ProcessValidationError, + is_protected_process, + normalize_process_name, + sanitize_domain, + sanitize_domains, +) +from .hosts import ( + LEGACY_MARKER_BEGIN, + LEGACY_MARKER_END, + MARKER_BEGIN, + MARKER_END, + HostsJournal, + HostsManager, + RecoveryResult, + SessionMeta, + build_managed_block, + has_managed_markers, + strip_managed_blocks, +) +from .supervisor import ( + HARDCORE_ANTICHEAT_BINARIES, + AntiCheatGuard, + ProcessSupervisor, + is_pid_alive, +) +from .privileges import ( + elevate_self, + flush_dns, + flush_dns_async, + is_elevated, + shield_mode_label, +) +from .config import ( + ConfigStore, + FocusProfile, + default_profiles, + dev_profile, + hardcore_profile, + load_config, + load_or_default, + save_config, + study_profile, +) +from .storage import ( + AnalyticsSummary, + DailyStat, + SessionRecord, + SessionStore, + generate_session_id, +) +from .timer import ( + MonotonicPhaseTimer, + generate_friction_token, +) + +__all__ = [ + "__version__", + "get_state_dir", + "get_config_path", + "get_sessions_path", + "get_journal_path", + "get_backup_path", + "get_gui_settings_path", + "get_default_hosts_path", + "DOH_BYPASS_DOMAINS", + "PROTECTED_PROCESS_NAMES", + "DomainValidationError", + "ProcessValidationError", + "sanitize_domain", + "sanitize_domains", + "is_protected_process", + "normalize_process_name", + "MARKER_BEGIN", + "MARKER_END", + "LEGACY_MARKER_BEGIN", + "LEGACY_MARKER_END", + "HostsJournal", + "SessionMeta", + "RecoveryResult", + "HostsManager", + "strip_managed_blocks", + "has_managed_markers", + "build_managed_block", + "HARDCORE_ANTICHEAT_BINARIES", + "ProcessSupervisor", + "AntiCheatGuard", + "is_pid_alive", + "is_elevated", + "shield_mode_label", + "elevate_self", + "flush_dns", + "flush_dns_async", + "FocusProfile", + "ConfigStore", + "default_profiles", + "study_profile", + "dev_profile", + "hardcore_profile", + "load_config", + "save_config", + "load_or_default", + "SessionRecord", + "DailyStat", + "AnalyticsSummary", + "SessionStore", + "generate_session_id", + "MonotonicPhaseTimer", + "generate_friction_token", +] diff --git a/focusflow_core/config.py b/focusflow_core/config.py new file mode 100644 index 0000000..7498949 --- /dev/null +++ b/focusflow_core/config.py @@ -0,0 +1,244 @@ +"""Unified profile and blocklist configuration shared identically with Go `pkg/profile`.""" + +from __future__ import annotations + +import dataclasses +import json +import os +import tempfile + +from .paths import get_config_path, get_state_dir +from .sanitize import ProcessValidationError, normalize_process_name, sanitize_domains + + +@dataclasses.dataclass +class FocusProfile: + name: str + description: str + blocked_domains: list[str] + blocked_processes: list[str] + default_work_minutes: int + default_break_minutes: int + + def to_dict(self) -> dict[str, object]: + return dataclasses.asdict(self) + + @classmethod + def from_dict(cls, key: str, data: dict[str, object]) -> "FocusProfile": + raw_domains = data.get("blocked_domains") or [] + raw_procs = data.get("blocked_processes") or [] + return cls( + name=str(data.get("name") or key), + description=str(data.get("description") or ""), + blocked_domains=sanitize_domains([str(x) for x in raw_domains]), + blocked_processes=_sanitize_process_list([str(x) for x in raw_procs]), + default_work_minutes=int(data.get("default_work_minutes", 25)), + default_break_minutes=int(data.get("default_break_minutes", 5)), + ) + + +@dataclasses.dataclass +class ConfigStore: + custom_domains: list[str] + custom_processes: list[str] + profiles: dict[str, FocusProfile] + + def to_dict(self) -> dict[str, object]: + return { + "custom_domains": sanitize_domains(self.custom_domains), + "custom_processes": _sanitize_process_list(self.custom_processes), + "profiles": {k: v.to_dict() for k, v in self.profiles.items()}, + } + + +def _sanitize_process_list(procs: list[str] | tuple[str, ...]) -> list[str]: + seen: set[str] = set() + out: list[str] = [] + for raw in procs: + try: + norm = normalize_process_name(raw) + except ProcessValidationError: + continue + if norm not in seen: + seen.add(norm) + out.append(norm) + return out + + +def dev_profile() -> FocusProfile: + return FocusProfile( + name="dev", + description="Developer Deep Work (Keeps GitHub & Docs open; blocks social media & gaming)", + blocked_domains=[ + "twitter.com", + "x.com", + "instagram.com", + "tiktok.com", + "reddit.com", + "facebook.com", + "netflix.com", + "twitch.tv", + ], + blocked_processes=[ + "discord.exe", + "spotify.exe", + "steam.exe", + "epicgameslauncher.exe", + "riotclientservices.exe", + ], + default_work_minutes=50, + default_break_minutes=10, + ) + + +def study_profile() -> FocusProfile: + return FocusProfile( + name="study", + description="Academic & Exam Preparation Mode (Zero entertainment)", + blocked_domains=[ + "youtube.com", + "instagram.com", + "tiktok.com", + "twitter.com", + "x.com", + "twitch.tv", + "kick.com", + "netflix.com", + "disneyplus.com", + "reddit.com", + ], + blocked_processes=[ + "steam.exe", + "discord.exe", + "spotify.exe", + "telegram.exe", + "whatsapp.exe", + "riotclientservices.exe", + "leagueclient.exe", + "valorant.exe", + ], + default_work_minutes=25, + default_break_minutes=5, + ) + + +def hardcore_profile() -> FocusProfile: + base = study_profile() + base.name = "hardcore" + base.description = "Aegis Lockdown - Maximum discipline with Anti-Cheat task suppression" + return base + + +def default_profiles() -> dict[str, FocusProfile]: + return { + "dev": dev_profile(), + "study": study_profile(), + "hardcore": hardcore_profile(), + } + + +def save_config(cfg: ConfigStore, state_dir: str | None = None) -> None: + resolved_dir = state_dir or get_state_dir() + os.makedirs(resolved_dir, exist_ok=True) + cfg_path = get_config_path(resolved_dir) + + if not cfg.profiles: + cfg.profiles = default_profiles() + cfg.custom_domains = sanitize_domains(cfg.custom_domains) + cfg.custom_processes = _sanitize_process_list(cfg.custom_processes) + + payload = (json.dumps(cfg.to_dict(), indent=2, ensure_ascii=False) + "\n").encode("utf-8") + fd, tmp_path = tempfile.mkstemp(prefix="config-", suffix=".tmp", dir=resolved_dir) + try: + with os.fdopen(fd, "wb") as f: + f.write(payload) + f.flush() + os.fsync(f.fileno()) + try: + os.chmod(tmp_path, 0o644) + except OSError: + pass + os.replace(tmp_path, cfg_path) + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + +def load_config(state_dir: str | None = None) -> ConfigStore: + resolved_dir = state_dir or get_state_dir() + cfg_path = get_config_path(resolved_dir) + + if not os.path.exists(cfg_path): + cfg = ConfigStore( + custom_domains=[], + custom_processes=[], + profiles=default_profiles(), + ) + save_config(cfg, state_dir=resolved_dir) + return cfg + + with open(cfg_path, "r", encoding="utf-8") as f: + raw = json.load(f) + + if not isinstance(raw, dict): + raise ValueError("invalid config.json root object") + + raw_domains = list(raw.get("custom_domains") or []) + list(raw.get("custom_sites") or []) + raw_procs = list(raw.get("custom_processes") or []) + list(raw.get("custom_apps") or []) + + profiles_map: dict[str, FocusProfile] = {} + raw_profiles = raw.get("profiles") + if isinstance(raw_profiles, dict): + for key, val in raw_profiles.items(): + if isinstance(val, dict): + profiles_map[str(key).lower()] = FocusProfile.from_dict(str(key).lower(), val) + + defaults = default_profiles() + for key, default_prof in defaults.items(): + if key not in profiles_map: + profiles_map[key] = default_prof + + return ConfigStore( + custom_domains=sanitize_domains([str(x) for x in raw_domains]), + custom_processes=_sanitize_process_list([str(x) for x in raw_procs]), + profiles=profiles_map, + ) + + +def load_or_default(name: str, state_dir: str | None = None) -> FocusProfile: + lower = (name or "study").strip().lower() + if lower == "coding": + lower = "dev" + elif lower == "lockdown": + lower = "hardcore" + + try: + cfg = load_config(state_dir=state_dir) + except Exception: + cfg = None + + if cfg is not None and lower in cfg.profiles: + prof = cfg.profiles[lower] + return FocusProfile( + name=prof.name, + description=prof.description, + blocked_domains=sanitize_domains([*prof.blocked_domains, *cfg.custom_domains]), + blocked_processes=_sanitize_process_list([*prof.blocked_processes, *cfg.custom_processes]), + default_work_minutes=prof.default_work_minutes, + default_break_minutes=prof.default_break_minutes, + ) + + if lower == "dev": + fallback = dev_profile() + elif lower == "hardcore": + fallback = hardcore_profile() + else: + fallback = study_profile() + + if cfg is not None: + fallback.blocked_domains = sanitize_domains([*fallback.blocked_domains, *cfg.custom_domains]) + fallback.blocked_processes = _sanitize_process_list([*fallback.blocked_processes, *cfg.custom_processes]) + return fallback diff --git a/focusflow_core/hosts.py b/focusflow_core/hosts.py new file mode 100644 index 0000000..760209b --- /dev/null +++ b/focusflow_core/hosts.py @@ -0,0 +1,656 @@ +"""Crash-safe SHA-256 atomic hosts engine with write-ahead journal and dual-stack IPv4/IPv6.""" + +from __future__ import annotations + +import ctypes +import dataclasses +import datetime +import hashlib +import json +import os +import sys +import tempfile +import time +from typing import Callable + +from .paths import ( + BACKUP_FILENAME, + JOURNAL_FILENAME, + get_default_hosts_path, + get_state_dir, + system_default_hosts_path, +) +from .privileges import flush_dns_async +from .sanitize import sanitize_domains +from .supervisor import is_pid_alive + +MARKER_BEGIN = "# --- BEGIN FOCUSFLOW MANAGED BLOCK ---" +MARKER_END = "# --- END FOCUSFLOW MANAGED BLOCK ---" +LEGACY_MARKER_BEGIN = "# --- FOCUSFLOW BLOCK START ---" +LEGACY_MARKER_END = "# --- FOCUSFLOW BLOCK END ---" + +REPLACEFILE_IGNORE_MERGE_ERRORS = 0x00000002 +MAX_WRITE_RETRIES = 5 +WRITE_RETRY_BACKOFF_SECONDS = 0.040 +WIN32_SHARING_WINERRORS = frozenset({32, 33}) + +if sys.platform == "win32": + from ctypes import wintypes + + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + _k32.ReplaceFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.LPCWSTR, + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.LPVOID, + ] + _k32.ReplaceFileW.restype = wintypes.BOOL + + +@dataclasses.dataclass +class HostsJournal: + original_sha256: str + backup_path: str + hosts_path: str + session_id: str + pid: int + started_at: str + expected_end_at: str + profile: str + + def to_dict(self) -> dict[str, object]: + return dataclasses.asdict(self) + + @classmethod + def from_dict(cls, data: dict[str, object]) -> "HostsJournal": + return cls( + original_sha256=str(data.get("original_sha256", "")), + backup_path=str(data.get("backup_path", "")), + hosts_path=str(data.get("hosts_path", "")), + session_id=str(data.get("session_id", "")), + pid=int(data.get("pid", 0)), + started_at=str(data.get("started_at", "")), + expected_end_at=str(data.get("expected_end_at", "")), + profile=str(data.get("profile", "study")), + ) + + +@dataclasses.dataclass +class SessionMeta: + session_id: str + pid: int = 0 + started_at: datetime.datetime | None = None + expected_end_at: datetime.datetime | None = None + profile: str = "study" + + +@dataclasses.dataclass +class RecoveryResult: + recovered: bool + used_fallback: bool = False + orphan_session_id: str = "" + active_owner_pid: int = 0 + restored_checksum: str = "" + reason: str = "clean" + + +def compute_bytes_sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def format_rfc3339_utc(dt: datetime.datetime) -> str: + if dt.tzinfo is None: + dt = dt.replace(tzinfo=datetime.timezone.utc) + else: + dt = dt.astimezone(datetime.timezone.utc) + return dt.replace(microsecond=0).isoformat().replace("+00:00", "Z") + + +def parse_rfc3339(ts: str) -> datetime.datetime | None: + s = (ts or "").strip() + if not s: + return None + if s.endswith("Z"): + s = s[:-1] + "+00:00" + try: + dt = datetime.datetime.fromisoformat(s) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=datetime.timezone.utc) + return dt.astimezone(datetime.timezone.utc) + except ValueError: + return None + + +def has_managed_markers(content: str) -> bool: + return any( + m in content + for m in (MARKER_BEGIN, MARKER_END, LEGACY_MARKER_BEGIN, LEGACY_MARKER_END) + ) + + +def detect_line_ending(content: str) -> str: + if "\r\n" in content: + return "\r\n" + if "\n" in content: + return "\n" + return "\r\n" if sys.platform == "win32" else "\n" + + +def _is_begin_marker_line(line: str) -> bool: + t = line.strip() + return ( + t == MARKER_BEGIN + or t == LEGACY_MARKER_BEGIN + or MARKER_BEGIN in line + or LEGACY_MARKER_BEGIN in line + ) + + +def _is_end_marker_line(line: str) -> bool: + t = line.strip() + return ( + t == MARKER_END + or t == LEGACY_MARKER_END + or MARKER_END in line + or LEGACY_MARKER_END in line + ) + + +def _is_likely_focusflow_sinkhole_line(line: str) -> bool: + t = line.strip() + if not t: + return True + if t.startswith("#"): + lower = t.lower() + return any(w in lower for w in ("focusflow", "managed", "sinkhole", "distraction")) + parts = t.split() + if len(parts) < 2: + return False + ip, host = parts[0], parts[1].lower() + if ip in ("0.0.0.0", "::"): + return True + if ip == "127.0.0.1" and host not in ("localhost", "localhost.localdomain"): + return True + return False + + +def strip_managed_blocks(content: str) -> str: + """Deterministically strip all current & legacy FocusFlow managed blocks. + + Safely handles truncated/missing end-markers without string-slice corruption, and + returns `content` byte-for-byte unchanged when no markers are present. + """ + if not has_managed_markers(content): + return content + + eol = detect_line_ending(content) + had_trailing_newline = content.endswith("\n") + + raw_lines = content.split("\n") + if had_trailing_newline and raw_lines and raw_lines[-1] == "": + raw_lines = raw_lines[:-1] + + lines = [l[:-1] if l.endswith("\r") else l for l in raw_lines] + kept: list[str] = [] + i = 0 + n = len(lines) + + while i < n: + line = lines[i] + if _is_begin_marker_line(line): + if kept and kept[-1].strip() == "": + kept.pop() + + end_idx = -1 + for j in range(i + 1, n): + if _is_end_marker_line(lines[j]): + end_idx = j + break + if _is_begin_marker_line(lines[j]): + break + + if end_idx >= 0: + i = end_idx + 1 + continue + + i += 1 + while i < n: + if _is_begin_marker_line(lines[i]): + break + if _is_end_marker_line(lines[i]): + i += 1 + break + if _is_likely_focusflow_sinkhole_line(lines[i]): + i += 1 + continue + break + continue + + if _is_end_marker_line(line): + i += 1 + continue + + kept.append(line) + i += 1 + + if not kept: + return "" + out = eol.join(kept) + if had_trailing_newline: + out += eol + return out + + +def build_managed_block(sanitized_domains: list[str], eol: str) -> str: + """Build dual-stack IPv4 (0.0.0.0) + IPv6 (::) sinkhole block.""" + rows: list[str] = [ + MARKER_BEGIN, + "# FocusFlow v2.1 - Dual-Stack Managed Sinkhole", + ] + for dom in sanitized_domains: + rows.append(f"0.0.0.0 {dom}") + if not dom.startswith("www."): + rows.append(f"0.0.0.0 www.{dom}") + rows.append(f":: {dom}") + if not dom.startswith("www."): + rows.append(f":: www.{dom}") + rows.append(MARKER_END) + return eol.join(rows) + eol + + +def _is_transient_sharing_error(exc: BaseException) -> bool: + if isinstance(exc, OSError): + winerr = getattr(exc, "winerror", None) + if winerr in WIN32_SHARING_WINERRORS: + return True + return False + + +def read_hosts_bytes_with_retry(hosts_path: str) -> bytes: + last_exc: Exception | None = None + for attempt in range(MAX_WRITE_RETRIES): + try: + with open(hosts_path, "rb") as f: + return f.read() + except OSError as exc: + last_exc = exc + if _is_transient_sharing_error(exc) and attempt + 1 < MAX_WRITE_RETRIES: + time.sleep(WRITE_RETRY_BACKOFF_SECONDS) + continue + raise + assert last_exc is not None + raise last_exc + + +def _write_atomic_state_bytes(path: str, data: bytes) -> None: + parent = os.path.dirname(path) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp_path = tempfile.mkstemp(prefix="ff-state-", suffix=".tmp", dir=parent) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + try: + os.chmod(tmp_path, 0o644) + except OSError: + pass + os.replace(tmp_path, path) + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + +def write_hosts_file_safe(hosts_path: str, content: bytes) -> None: + """Write hosts file preserving Windows DACLs / POSIX modes, fsyncing, and retrying sharing locks.""" + parent = os.path.dirname(hosts_path) or "." + os.makedirs(parent, exist_ok=True) + + target_exists = os.path.exists(hosts_path) + target_mode = 0o644 + if target_exists and sys.platform != "win32": + try: + target_mode = os.stat(hosts_path).st_mode & 0o777 or 0o644 + except OSError: + target_mode = 0o644 + + fd, tmp_path = tempfile.mkstemp(prefix="focusflow-hosts-", suffix=".tmp", dir=parent) + try: + with os.fdopen(fd, "wb") as f: + f.write(content) + f.flush() + os.fsync(f.fileno()) + if sys.platform != "win32": + os.chmod(tmp_path, target_mode) + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + if sys.platform == "win32" and target_exists: + last_winerr = 0 + for attempt in range(MAX_WRITE_RETRIES): + ok = bool( + _k32.ReplaceFileW( + hosts_path, + tmp_path, + None, + REPLACEFILE_IGNORE_MERGE_ERRORS, + None, + None, + ) + ) + if ok: + return + last_winerr = ctypes.get_last_error() + if attempt + 1 < MAX_WRITE_RETRIES: + time.sleep(WRITE_RETRY_BACKOFF_SECONDS) + + try: + os.unlink(tmp_path) + except OSError: + pass + + last_exc: OSError | None = None + for attempt in range(MAX_WRITE_RETRIES): + try: + with open(hosts_path, "r+b") as f: + f.seek(0) + f.write(content) + f.truncate() + f.flush() + os.fsync(f.fileno()) + return + except OSError as exc: + last_exc = exc + if attempt + 1 < MAX_WRITE_RETRIES: + time.sleep(WRITE_RETRY_BACKOFF_SECONDS) + continue + raise + if last_exc is not None: + raise last_exc + raise OSError(last_winerr, f"ReplaceFileW failed on {hosts_path}") + + last_err: OSError | None = None + for attempt in range(MAX_WRITE_RETRIES): + try: + os.replace(tmp_path, hosts_path) + return + except OSError as exc: + last_err = exc + if attempt + 1 < MAX_WRITE_RETRIES: + time.sleep(WRITE_RETRY_BACKOFF_SECONDS) + continue + try: + os.unlink(tmp_path) + except OSError: + pass + raise + if last_err is not None: + raise last_err + + +class HostsManager: + """Unified crash-safe SHA-256 hosts manager identical to Go `engine.HostsManager`.""" + + def __init__(self, hosts_path: str | None = None, state_dir: str | None = None) -> None: + resolved_hosts = os.path.normpath(hosts_path) if hosts_path else get_default_hosts_path() + if state_dir: + resolved_state = os.path.normpath(state_dir) + elif os.environ.get("FOCUSFLOW_HOME", "").strip(): + resolved_state = get_state_dir() + elif resolved_hosts != os.path.normpath(system_default_hosts_path()): + resolved_state = os.path.dirname(resolved_hosts) or "." + else: + resolved_state = get_state_dir() + + self.hosts_path = resolved_hosts + self.state_dir = resolved_state + self.backup_path = os.path.join(resolved_state, BACKUP_FILENAME) + self.journal_path = os.path.join(resolved_state, JOURNAL_FILENAME) + + def compute_sha256(self, path: str) -> str: + with open(path, "rb") as f: + return compute_bytes_sha256(f.read()) + + def backup(self) -> str: + if not os.path.exists(self.hosts_path): + raise FileNotFoundError(f"hosts file not found at {self.hosts_path}") + raw_text = read_hosts_bytes_with_retry(self.hosts_path).decode("utf-8", errors="surrogateescape") + clean_text = strip_managed_blocks(raw_text) + clean_bytes = clean_text.encode("utf-8", errors="surrogateescape") + _write_atomic_state_bytes(self.backup_path, clean_bytes) + return compute_bytes_sha256(clean_bytes) + + def load_journal(self) -> HostsJournal | None: + if not os.path.exists(self.journal_path): + return None + with open(self.journal_path, "r", encoding="utf-8") as f: + raw = json.load(f) + if not isinstance(raw, dict): + raise ValueError("corrupt journal structure") + return HostsJournal.from_dict(raw) + + def _write_journal(self, journal: HostsJournal) -> None: + payload = (json.dumps(journal.to_dict(), indent=2) + "\n").encode("utf-8") + _write_atomic_state_bytes(self.journal_path, payload) + + def apply_blocklist( + self, + domains: list[str] | tuple[str, ...], + meta: SessionMeta | None = None, + ) -> bool: + clean_domains = sanitize_domains(domains) + if not clean_domains: + return False + + if not os.path.exists(self.hosts_path): + raise FileNotFoundError(f"hosts file not found at {self.hosts_path}") + + raw_bytes = read_hosts_bytes_with_retry(self.hosts_path) + raw_text = raw_bytes.decode("utf-8", errors="surrogateescape") + clean_baseline = strip_managed_blocks(raw_text) + clean_bytes = clean_baseline.encode("utf-8", errors="surrogateescape") + baseline_sha = compute_bytes_sha256(clean_bytes) + + need_fresh_backup = True + try: + existing_journal = self.load_journal() + if existing_journal and existing_journal.original_sha256 and os.path.exists(self.backup_path): + with open(self.backup_path, "rb") as f: + bak_bytes = f.read() + bak_text = bak_bytes.decode("utf-8", errors="surrogateescape") + if not has_managed_markers(bak_text) and compute_bytes_sha256(bak_bytes) == existing_journal.original_sha256: + baseline_sha = existing_journal.original_sha256 + need_fresh_backup = False + except Exception: + need_fresh_backup = True + + if need_fresh_backup: + _write_atomic_state_bytes(self.backup_path, clean_bytes) + + now_utc = datetime.datetime.now(datetime.timezone.utc) + if meta is None: + meta = SessionMeta( + session_id=os.urandom(8).hex(), + pid=os.getpid(), + started_at=now_utc, + expected_end_at=now_utc + datetime.timedelta(hours=2), + profile="study", + ) + + pid = meta.pid if meta.pid > 0 else os.getpid() + started_at = meta.started_at or now_utc + expected_end_at = meta.expected_end_at or (started_at + datetime.timedelta(minutes=60)) + session_id = meta.session_id or os.urandom(8).hex() + profile = meta.profile or "study" + + journal = HostsJournal( + original_sha256=baseline_sha, + backup_path=self.backup_path, + hosts_path=self.hosts_path, + session_id=session_id, + pid=pid, + started_at=format_rfc3339_utc(started_at), + expected_end_at=format_rfc3339_utc(expected_end_at), + profile=profile, + ) + + # Write-ahead journal persisted BEFORE modifying system hosts + self._write_journal(journal) + + eol = detect_line_ending(clean_baseline) + block = build_managed_block(clean_domains, eol) + trimmed_base = clean_baseline.rstrip("\r\n") + new_text = f"{trimmed_base}{eol}{eol}{block}" if trimmed_base else block + write_hosts_file_safe(self.hosts_path, new_text.encode("utf-8", errors="surrogateescape")) + return True + + def verify_or_reapply( + self, + domains: list[str] | tuple[str, ...], + meta: SessionMeta | None = None, + ) -> bool: + """Check mid-session hosts integrity and re-apply blocklist if tampered. Returns True if tampered.""" + clean_domains = sanitize_domains(domains) + if not clean_domains: + return False + + raw_text = read_hosts_bytes_with_retry(self.hosts_path).decode("utf-8", errors="surrogateescape") + if MARKER_BEGIN not in raw_text or MARKER_END not in raw_text: + self.apply_blocklist(clean_domains, meta=meta) + return True + + for dom in clean_domains: + if f"0.0.0.0 {dom}" not in raw_text or f":: {dom}" not in raw_text: + self.apply_blocklist(clean_domains, meta=meta) + return True + return False + + def _restore_hosts_from_backup_or_strip(self) -> bool: + """Restore hosts via SHA-256 verified backup or deterministic marker stripping fallback. + + Returns True if fallback marker stripping was used, False if .bak matched SHA-256. + """ + journal: HostsJournal | None = None + try: + journal = self.load_journal() + except Exception: + journal = None + + bak_path = journal.backup_path if (journal and journal.backup_path) else self.backup_path + if os.path.exists(bak_path): + try: + with open(bak_path, "rb") as f: + bak_bytes = f.read() + bak_text = bak_bytes.decode("utf-8", errors="surrogateescape") + bak_clean = not has_managed_markers(bak_text) + hash_matches = True + if journal and journal.original_sha256: + hash_matches = compute_bytes_sha256(bak_bytes) == journal.original_sha256 + if bak_clean and hash_matches: + write_hosts_file_safe(self.hosts_path, bak_bytes) + return False + except OSError: + pass + + if os.path.exists(self.hosts_path): + raw_text = read_hosts_bytes_with_retry(self.hosts_path).decode("utf-8", errors="surrogateescape") + clean_text = strip_managed_blocks(raw_text) + write_hosts_file_safe(self.hosts_path, clean_text.encode("utf-8", errors="surrogateescape")) + return True + + return False + + def _cleanup_state_artifacts(self) -> None: + for p in (self.journal_path, self.backup_path, f"{self.hosts_path}.focusflow.bak"): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass + + def rollback(self) -> None: + self._restore_hosts_from_backup_or_strip() + self._cleanup_state_artifacts() + + def recover_if_orphaned( + self, + on_orphan_session: Callable[[str], None] | None = None, + now: datetime.datetime | None = None, + flush_async: bool = True, + ) -> RecoveryResult: + """Automatically recover crashed/rebooted/expired hosts blocks on startup.""" + now_utc = (now or datetime.datetime.now(datetime.timezone.utc)).astimezone(datetime.timezone.utc) + + has_corrupt_journal = False + journal: HostsJournal | None = None + if os.path.exists(self.journal_path): + try: + journal = self.load_journal() + except Exception: + has_corrupt_journal = True + + hosts_has_markers = False + if os.path.exists(self.hosts_path): + try: + txt = read_hosts_bytes_with_retry(self.hosts_path).decode("utf-8", errors="surrogateescape") + hosts_has_markers = has_managed_markers(txt) + except OSError: + hosts_has_markers = False + + if journal is None and not has_corrupt_journal and not hosts_has_markers: + return RecoveryResult(recovered=False, reason="clean") + + reason = "stray_markers_without_journal" + orphan_session_id = "" + + if journal is not None: + orphan_session_id = journal.session_id + exp_dt = parse_rfc3339(journal.expected_end_at) + expired = exp_dt is not None and now_utc > exp_dt + pid_alive = journal.pid > 0 and is_pid_alive(journal.pid) + + if pid_alive and not expired: + return RecoveryResult( + recovered=False, + active_owner_pid=journal.pid, + reason="active_session_alive", + ) + reason = f"owner_pid_{journal.pid}_dead" if not pid_alive else "session_lease_expired" + elif has_corrupt_journal: + reason = "corrupt_journal" + + used_fallback = self._restore_hosts_from_backup_or_strip() + self._cleanup_state_artifacts() + + if on_orphan_session is not None: + on_orphan_session(orphan_session_id) + + if flush_async: + flush_dns_async() + + checksum = self.compute_sha256(self.hosts_path) if os.path.exists(self.hosts_path) else "" + return RecoveryResult( + recovered=True, + used_fallback=used_fallback, + orphan_session_id=orphan_session_id, + restored_checksum=checksum, + reason=reason, + ) + + def is_active(self) -> bool: + if not os.path.exists(self.hosts_path): + return False + try: + txt = read_hosts_bytes_with_retry(self.hosts_path).decode("utf-8", errors="surrogateescape") + return MARKER_BEGIN in txt or LEGACY_MARKER_BEGIN in txt + except OSError: + return False diff --git a/focusflow_core/paths.py b/focusflow_core/paths.py new file mode 100644 index 0000000..74e824d --- /dev/null +++ b/focusflow_core/paths.py @@ -0,0 +1,79 @@ +"""Unified state directory and system file path resolution shared with the Go CLI.""" + +from __future__ import annotations + +import os +import sys + +DEFAULT_WINDOWS_HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts" +DEFAULT_POSIX_HOSTS_PATH = "/etc/hosts" + +BACKUP_FILENAME = "hosts.focusflow.bak" +JOURNAL_FILENAME = "hosts.focusflow.journal.json" +CONFIG_FILENAME = "config.json" +SESSIONS_FILENAME = "sessions.json" +GUI_SETTINGS_FILENAME = "gui_settings.json" + + +def get_state_dir() -> str: + """Resolve FocusFlow state directory identically to Go `storage.GetStateDir()`. + + Priority: + 1. FOCUSFLOW_HOME environment override + 2. Windows: %APPDATA%\\FocusFlow (or ~/AppData/Roaming/FocusFlow) + 3. POSIX: $XDG_CONFIG_HOME/focusflow (or ~/.config/focusflow) + 4. Fallback: .focusflow + """ + override = os.environ.get("FOCUSFLOW_HOME", "").strip() + if override: + return os.path.normpath(override) + + if sys.platform == "win32": + appdata = os.environ.get("APPDATA", "").strip() + if appdata: + return os.path.join(appdata, "FocusFlow") + home = os.path.expanduser("~") + if home and home != "~": + return os.path.join(home, "AppData", "Roaming", "FocusFlow") + return ".focusflow" + + xdg = os.environ.get("XDG_CONFIG_HOME", "").strip() + if xdg: + return os.path.join(xdg, "focusflow") + home = os.path.expanduser("~") + if home and home != "~": + return os.path.join(home, ".config", "focusflow") + return ".focusflow" + + +def system_default_hosts_path() -> str: + if sys.platform == "win32": + return DEFAULT_WINDOWS_HOSTS_PATH + return DEFAULT_POSIX_HOSTS_PATH + + +def get_default_hosts_path() -> str: + override = os.environ.get("FOCUSFLOW_HOSTS_PATH", "").strip() + if override: + return os.path.normpath(override) + return system_default_hosts_path() + + +def get_config_path(state_dir: str | None = None) -> str: + return os.path.join(state_dir or get_state_dir(), CONFIG_FILENAME) + + +def get_sessions_path(state_dir: str | None = None) -> str: + return os.path.join(state_dir or get_state_dir(), SESSIONS_FILENAME) + + +def get_journal_path(state_dir: str | None = None) -> str: + return os.path.join(state_dir or get_state_dir(), JOURNAL_FILENAME) + + +def get_backup_path(state_dir: str | None = None) -> str: + return os.path.join(state_dir or get_state_dir(), BACKUP_FILENAME) + + +def get_gui_settings_path(state_dir: str | None = None) -> str: + return os.path.join(state_dir or get_state_dir(), GUI_SETTINGS_FILENAME) diff --git a/focusflow_core/privileges.py b/focusflow_core/privileges.py new file mode 100644 index 0000000..453a73f --- /dev/null +++ b/focusflow_core/privileges.py @@ -0,0 +1,144 @@ +"""Privilege inspection, UAC/sudo self-elevation, and non-blocking DNS cache flushing.""" + +from __future__ import annotations + +import ctypes +import os +import subprocess +import sys +import threading + +CREATE_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0 + + +def is_elevated() -> bool: + """Return True if the current process holds Administrator (Windows) or root (POSIX) privileges.""" + if sys.platform == "win32": + try: + shell32 = ctypes.WinDLL("shell32", use_last_error=True) + shell32.IsUserAnAdmin.argtypes = [] + shell32.IsUserAnAdmin.restype = ctypes.wintypes.BOOL if hasattr(ctypes, "wintypes") else ctypes.c_int + return bool(shell32.IsUserAnAdmin()) + except Exception: + return False + try: + return os.geteuid() == 0 + except AttributeError: + return False + + +def shield_mode_label(elevated: bool | None = None) -> str: + """Return honest shield capability badge string.""" + if elevated is None: + elevated = is_elevated() + return "FULL SHIELD [HOSTS + PROC]" if elevated else "PROCESS-ONLY [UNPRIVILEGED]" + + +def build_elevation_cmdline(script_path: str | None = None, extra_args: list[str] | None = None) -> str: + """Build safely quoted Win32 command-line argument string preserving paths with spaces.""" + target = os.path.abspath(script_path or sys.argv[0]) + args = list(extra_args) if extra_args is not None else [a for a in sys.argv[1:] if a != "--elevate"] + return subprocess.list2cmdline([target, *args]) + + +def elevate_self( + script_path: str | None = None, + extra_args: list[str] | None = None, + executable: str | None = None, +) -> bool: + """Relaunch the current Python entrypoint with Administrator/root privileges. + + Uses ShellExecuteW(None, "runas", ...) with subprocess.list2cmdline on Windows + so workspace/user paths containing spaces never break. + """ + exe = executable or sys.executable + params = build_elevation_cmdline(script_path=script_path, extra_args=extra_args) + cwd = os.getcwd() + + if sys.platform == "win32": + from ctypes import wintypes + + # Prefer pythonw.exe when launching GUI without console flash if running from FocusFlowGUI.py + target_name = os.path.basename(script_path or sys.argv[0]).lower() + if executable is None and target_name.endswith("gui.py") and exe.lower().endswith("python.exe"): + candidate_w = exe[:-10] + "pythonw.exe" + if os.path.exists(candidate_w): + exe = candidate_w + + shell32 = ctypes.WinDLL("shell32", use_last_error=True) + shell32.ShellExecuteW.argtypes = [ + wintypes.HWND, + wintypes.LPCWSTR, + wintypes.LPCWSTR, + wintypes.LPCWSTR, + wintypes.LPCWSTR, + ctypes.c_int, + ] + shell32.ShellExecuteW.restype = ctypes.c_void_p + + res = shell32.ShellExecuteW(None, "runas", exe, params, cwd, 1) + return int(res or 0) > 32 + + target = os.path.abspath(script_path or sys.argv[0]) + args = list(extra_args) if extra_args is not None else [a for a in sys.argv[1:] if a != "--elevate"] + try: + proc = subprocess.Popen(["sudo", exe, target, *args], cwd=cwd) + return proc.pid > 0 + except Exception: + return False + + +def flush_dns() -> bool: + """Synchronously flush local OS DNS resolver cache.""" + try: + if sys.platform == "win32": + res = subprocess.run( + ["ipconfig", "/flushdns"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + creationflags=CREATE_NO_WINDOW, + timeout=10, + check=False, + ) + return res.returncode == 0 + if sys.platform == "darwin": + subprocess.run( + ["dscacheutil", "-flushcache"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + subprocess.run( + ["killall", "-HUP", "mDNSResponder"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + return True + res = subprocess.run( + ["resolvectl", "flush-caches"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + if res.returncode != 0: + subprocess.run( + ["systemd-resolve", "--flush-caches"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + return True + except Exception: + return False + + +def flush_dns_async() -> threading.Thread: + """Offload DNS cache purge to a daemon thread so GUI event loops never stall.""" + t = threading.Thread(target=flush_dns, name="FocusFlowDNSFlush", daemon=True) + t.start() + return t diff --git a/focusflow_core/sanitize.py b/focusflow_core/sanitize.py new file mode 100644 index 0000000..7d23964 --- /dev/null +++ b/focusflow_core/sanitize.py @@ -0,0 +1,238 @@ +"""Strict RFC-1123 domain sanitization, Anti-DoH list, and protected process denylist.""" + +from __future__ import annotations + +import ipaddress +import re + +DOH_BYPASS_DOMAINS: tuple[str, ...] = ( + "cloudflare-dns.com", + "one.one.one.one", + "chrome.cloudflare-dns.com", + "mozilla.cloudflare-dns.com", + "dns.google", + "dns.google.com", + "dns.quad9.net", + "doh.opendns.com", + "dns.adguard-dns.com", + "dns.nextdns.io", + "doh.cleanbrowsing.org", + "doh.dns.sb", + "freedns.controld.com", +) + +RESERVED_EXACT_DOMAINS: frozenset[str] = frozenset( + { + "localhost", + "localhost.localdomain", + "localdomain", + "local", + "broadcasthost", + "ip6-localhost", + "ip6-loopback", + "ip6-localnet", + "ip6-mcastprefix", + "ip6-allnodes", + "ip6-allrouters", + "ip6-allhosts", + } +) + +_PROTECTED_BASE_NAMES: tuple[str, ...] = ( + "csrss", + "smss", + "lsass", + "services", + "svchost", + "wininit", + "winlogon", + "dwm", + "explorer", + "sihost", + "fontdrvhost", + "focusflow", + "python", + "python3", + "pythonw", + "conhost", + "wt", + "init", + "systemd", + "launchd", + "kernel_task", +) + +PROTECTED_PROCESS_NAMES: frozenset[str] = frozenset( + name + for base in _PROTECTED_BASE_NAMES + for name in (base.lower(), f"{base.lower()}.exe") +) + +_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$") + + +class DomainValidationError(ValueError): + """Raised when a domain fails strict RFC-1123 or sinkhole safety validation.""" + + +class ProcessValidationError(ValueError): + """Raised when a process executable name is invalid or protected.""" + + +def _is_ip_literal(candidate: str) -> bool: + try: + ipaddress.ip_address(candidate) + return True + except ValueError: + return False + + +def sanitize_domain(raw: str) -> str: + """Strictly normalize and validate a domain name per RFC-1123. + + Strips http(s)://, paths, query strings, fragments, valid ports, outer spaces, and leading www. + Rejects newlines, control characters, embedded spaces, IP literals, localhost, localdomain, and *.local. + """ + if not isinstance(raw, str): + raise DomainValidationError("domain must be a string") + + for ch in raw: + code = ord(ch) + if code < 0x20 or code == 0x7F: + raise DomainValidationError("domain contains illegal control characters") + + s = raw.strip(" ") + if not s or s.startswith("#"): + raise DomainValidationError("domain cannot be empty") + + if any(ws in s for ws in (" ", "\t", "\r", "\n")): + raise DomainValidationError("domain contains embedded whitespace") + + s = s.lower() + + if s.startswith("https://"): + s = s[len("https://") :] + elif s.startswith("http://"): + s = s[len("http://") :] + elif "://" in s: + raise DomainValidationError("unsupported URL scheme") + + for sep in ("/", "?", "#"): + idx = s.find(sep) + if idx >= 0: + s = s[:idx] + + if not s: + raise DomainValidationError("domain cannot be empty") + + if "[" in s or "]" in s: + raise DomainValidationError("IPv6 literals cannot be blocked") + if "@" in s: + raise DomainValidationError("userinfo is not allowed in domain") + + colon_count = s.count(":") + if colon_count > 1: + raise DomainValidationError("IPv6 literals cannot be blocked") + if colon_count == 1: + host_part, port_part = s.split(":", 1) + if not port_part.isdigit(): + raise DomainValidationError("invalid port in domain") + port_num = int(port_part) + if port_num < 1 or port_num > 65535: + raise DomainValidationError("port out of range") + s = host_part + + if s.endswith("."): + s = s[:-1] + if not s: + raise DomainValidationError("domain cannot be empty") + + if _is_ip_literal(s): + raise DomainValidationError("IP literals cannot be blocked") + + if s in RESERVED_EXACT_DOMAINS or s.endswith((".local", ".localhost", ".localdomain")): + raise DomainValidationError("reserved or local domain cannot be blocked") + + if s.startswith("www."): + rest = s[4:] + if "." in rest: + s = rest + + if _is_ip_literal(s): + raise DomainValidationError("IP literals cannot be blocked") + if s in RESERVED_EXACT_DOMAINS or s.endswith((".local", ".localhost", ".localdomain")): + raise DomainValidationError("reserved or local domain cannot be blocked") + + if len(s) > 253 or "." not in s: + raise DomainValidationError("invalid RFC-1123 domain") + + labels = s.split(".") + if len(labels) < 2: + raise DomainValidationError("domain must have at least two labels") + + for label in labels: + if not label or len(label) > 63: + raise DomainValidationError("invalid domain label length") + if not _LABEL_RE.match(label): + raise DomainValidationError("invalid RFC-1123 label characters") + + if labels[-1].isdigit(): + raise DomainValidationError("numeric TLD or malformed IPv4 literal is not allowed") + + return s + + +def sanitize_domains(domains: list[str] | tuple[str, ...]) -> list[str]: + """Sanitize and deduplicate a list of domains while preserving deterministic order.""" + seen: set[str] = set() + out: list[str] = [] + for raw in domains: + try: + clean = sanitize_domain(raw) + except DomainValidationError: + continue + if clean not in seen: + seen.add(clean) + out.append(clean) + return out + + +def is_protected_process(name: str) -> bool: + """Return True if process name matches the critical Windows/POSIX system & host denylist.""" + if not isinstance(name, str): + return False + cleaned = name.strip().lower() + if not cleaned: + return False + cleaned = cleaned.replace("\\", "/").rsplit("/", 1)[-1] + return cleaned in PROTECTED_PROCESS_NAMES + + +def normalize_process_name(raw: str) -> str: + """Validate and canonicalize a process name (appending .exe) while enforcing the denylist.""" + if not isinstance(raw, str): + raise ProcessValidationError("process name must be a string") + for ch in raw: + code = ord(ch) + if code < 0x20 or code == 0x7F: + raise ProcessValidationError("process name contains control characters") + + trimmed = raw.strip().lower() + if not trimmed: + raise ProcessValidationError("process name cannot be empty") + if any(bad in trimmed for bad in ("/", "\\", ":", "*", "?", '"', "<", ">", "|", " ")) or ".." in trimmed: + raise ProcessValidationError("invalid process executable name") + + if is_protected_process(trimmed): + raise ProcessValidationError(f"protected system or host process cannot be blocked: {trimmed}") + + if not trimmed.endswith(".exe"): + trimmed = f"{trimmed}.exe" + + if is_protected_process(trimmed): + raise ProcessValidationError(f"protected system or host process cannot be blocked: {trimmed}") + + base = trimmed[:-4] + if not base: + raise ProcessValidationError("invalid process executable name") + return trimmed diff --git a/focusflow_core/storage.py b/focusflow_core/storage.py new file mode 100644 index 0000000..e274d28 --- /dev/null +++ b/focusflow_core/storage.py @@ -0,0 +1,410 @@ +"""Unified sessions.json telemetry store, real streak/analytics engine, and JSON/CSV exporters.""" + +from __future__ import annotations + +import csv +import dataclasses +import datetime +import io +import json +import os +import secrets +import tempfile +import threading + +from .hosts import format_rfc3339_utc +from .paths import get_sessions_path, get_state_dir + + +def generate_session_id() -> str: + return secrets.token_hex(8) + + +@dataclasses.dataclass +class SessionRecord: + profile: str + start_time: str + duration_minutes: int + completed: bool + blocked_count: int = 0 + id: str = "" + end_time: str = "" + planned_minutes: int = 0 + status: str = "" + + def to_dict(self) -> dict[str, object]: + out: dict[str, object] = {} + if self.id: + out["id"] = self.id + out["profile"] = self.profile + out["start_time"] = self.start_time + if self.end_time: + out["end_time"] = self.end_time + out["duration_minutes"] = int(self.duration_minutes) + if self.planned_minutes > 0: + out["planned_minutes"] = int(self.planned_minutes) + out["completed"] = bool(self.completed) + if self.status: + out["status"] = self.status + out["blocked_count"] = int(self.blocked_count) + return out + + @classmethod + def from_dict(cls, data: dict[str, object]) -> "SessionRecord": + return cls( + id=str(data.get("id", "")), + profile=str(data.get("profile", "study")), + start_time=str(data.get("start_time", "")), + end_time=str(data.get("end_time", "")), + duration_minutes=int(data.get("duration_minutes", 0)), + planned_minutes=int(data.get("planned_minutes", 0)), + completed=bool(data.get("completed", False)), + status=str(data.get("status", "")), + blocked_count=int(data.get("blocked_count", 0)), + ) + + +@dataclasses.dataclass +class DailyStat: + date: str + minutes: int + sprints: int + + def to_dict(self) -> dict[str, object]: + return dataclasses.asdict(self) + + +@dataclasses.dataclass +class AnalyticsSummary: + completed_sprints: int + attempted_sprints: int + aborted_sprints: int + completion_rate: float + total_minutes: int + total_hours: float + total_blocked: int + active_streak_days: int + daily: list[DailyStat] + + def to_dict(self) -> dict[str, object]: + return { + "completed_sprints": self.completed_sprints, + "attempted_sprints": self.attempted_sprints, + "aborted_sprints": self.aborted_sprints, + "completion_rate": round(self.completion_rate, 2), + "total_minutes": self.total_minutes, + "total_hours": round(self.total_hours, 2), + "total_blocked": self.total_blocked, + "active_streak_days": self.active_streak_days, + "daily": [d.to_dict() for d in self.daily], + } + + +def _parse_session_local_date(ts: str, tz: datetime.tzinfo | None) -> str | None: + s = (ts or "").strip() + if not s: + return None + if len(s) == 10 and s[4] == "-" and s[7] == "-": + return s + iso = s[:-1] + "+00:00" if s.endswith("Z") else s + try: + dt = datetime.datetime.fromisoformat(iso) + if dt.tzinfo is not None and tz is not None: + dt = dt.astimezone(tz) + return dt.strftime("%Y-%m-%d") + except ValueError: + if len(s) >= 10 and s[4] == "-" and s[7] == "-": + return s[:10] + return None + + +class SessionStore: + """Thread-safe atomic `sessions.json` store shared identically between Go CLI and Python GUI.""" + + def __init__(self, state_dir: str | None = None) -> None: + self.state_dir = state_dir or get_state_dir() + os.makedirs(self.state_dir, exist_ok=True) + self.path = get_sessions_path(self.state_dir) + self._lock = threading.Lock() + + def _read_locked(self) -> list[SessionRecord]: + if not os.path.exists(self.path): + return [] + try: + with open(self.path, "r", encoding="utf-8") as f: + raw = json.load(f) + if isinstance(raw, dict) and isinstance(raw.get("sessions"), list): + return [SessionRecord.from_dict(item) for item in raw["sessions"] if isinstance(item, dict)] + except Exception: + return [] + return [] + + def _write_locked(self, sessions: list[SessionRecord]) -> None: + os.makedirs(self.state_dir, exist_ok=True) + payload_obj = {"sessions": [s.to_dict() for s in sessions]} + payload = (json.dumps(payload_obj, indent=2, ensure_ascii=False) + "\n").encode("utf-8") + + fd, tmp_path = tempfile.mkstemp(prefix="sessions-", suffix=".tmp", dir=self.state_dir) + try: + with os.fdopen(fd, "wb") as f: + f.write(payload) + f.flush() + os.fsync(f.fileno()) + try: + os.chmod(tmp_path, 0o644) + except OSError: + pass + os.replace(tmp_path, self.path) + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + + def load_sessions(self) -> list[SessionRecord]: + with self._lock: + return list(self._read_locked()) + + def start_session( + self, + session_id: str, + profile: str, + planned_minutes: int, + start_time: datetime.datetime | None = None, + ) -> str: + """Record `start_time` immediately when a focus sprint begins.""" + sid = session_id or generate_session_id() + started = start_time or datetime.datetime.now(datetime.timezone.utc) + rec = SessionRecord( + id=sid, + profile=profile, + start_time=format_rfc3339_utc(started), + duration_minutes=0, + planned_minutes=max(0, int(planned_minutes)), + completed=False, + status="running", + blocked_count=0, + ) + with self._lock: + sessions = self._read_locked() + sessions.append(rec) + self._write_locked(sessions) + return sid + + def finalize_session( + self, + session_id: str, + profile: str, + duration_minutes: int, + completed: bool, + blocked_count: int = 0, + status: str = "", + start_time: datetime.datetime | None = None, + end_time: datetime.datetime | None = None, + ) -> None: + """Update running session upon completion or early abort.""" + ended = end_time or datetime.datetime.now(datetime.timezone.utc) + resolved_status = status or ("completed" if completed else "aborted") + + with self._lock: + sessions = self._read_locked() + updated = False + if session_id: + for idx in range(len(sessions) - 1, -1, -1): + if sessions[idx].id == session_id: + sessions[idx].duration_minutes = max(0, int(duration_minutes)) + sessions[idx].completed = bool(completed) + sessions[idx].status = resolved_status + sessions[idx].blocked_count = max(0, int(blocked_count)) + sessions[idx].end_time = format_rfc3339_utc(ended) + if not sessions[idx].start_time and start_time is not None: + sessions[idx].start_time = format_rfc3339_utc(start_time) + updated = True + break + + if not updated: + started = start_time or (ended - datetime.timedelta(minutes=max(0, int(duration_minutes)))) + sessions.append( + SessionRecord( + id=session_id, + profile=profile, + start_time=format_rfc3339_utc(started), + end_time=format_rfc3339_utc(ended), + duration_minutes=max(0, int(duration_minutes)), + completed=bool(completed), + status=resolved_status, + blocked_count=max(0, int(blocked_count)), + ) + ) + self._write_locked(sessions) + + def mark_orphaned_session( + self, + session_id: str = "", + now: datetime.datetime | None = None, + ) -> int: + """Mark crashed/orphaned running sessions as completed=False, status='orphaned'.""" + ended = now or datetime.datetime.now(datetime.timezone.utc) + marked = 0 + with self._lock: + sessions = self._read_locked() + for rec in sessions: + if (session_id and rec.id == session_id) or rec.status == "running": + if rec.status == "running" or (session_id and rec.id == session_id and (rec.completed or not rec.status)): + rec.completed = False + rec.status = "orphaned" + if not rec.end_time: + rec.end_time = format_rfc3339_utc(ended) + marked += 1 + if marked > 0: + self._write_locked(sessions) + return marked + + def compute_analytics( + self, + days: int = 7, + now: datetime.datetime | None = None, + ) -> AnalyticsSummary: + """Compute genuine streak, total focus hours, completion rate, and N-day bar chart.""" + window = days if days > 0 else 7 + ref_now = now or datetime.datetime.now().astimezone() + tz = ref_now.tzinfo + today = ref_now.date() + + sessions = self.load_sessions() + daily_min: dict[str, int] = {} + daily_sprints: dict[str, int] = {} + completed_dates: set[str] = set() + + completed_count = 0 + attempted_count = 0 + aborted_count = 0 + total_minutes = 0 + total_blocked = 0 + + for rec in sessions: + total_blocked += max(0, rec.blocked_count) + if rec.status == "running": + continue + attempted_count += 1 + if rec.completed: + completed_count += 1 + total_minutes += max(0, rec.duration_minutes) + d_str = _parse_session_local_date(rec.start_time, tz) + if d_str: + daily_min[d_str] = daily_min.get(d_str, 0) + max(0, rec.duration_minutes) + daily_sprints[d_str] = daily_sprints.get(d_str, 0) + 1 + if rec.duration_minutes > 0: + completed_dates.add(d_str) + else: + aborted_count += 1 + + completion_rate = (completed_count / attempted_count * 100.0) if attempted_count > 0 else 0.0 + + streak = 0 + today_str = today.strftime("%Y-%m-%d") + yesterday = today - datetime.timedelta(days=1) + yesterday_str = yesterday.strftime("%Y-%m-%d") + + cursor: datetime.date | None = None + if today_str in completed_dates: + cursor = today + elif yesterday_str in completed_dates: + cursor = yesterday + + while cursor is not None and cursor.strftime("%Y-%m-%d") in completed_dates: + streak += 1 + cursor = cursor - datetime.timedelta(days=1) + + daily: list[DailyStat] = [] + for offset in range(window - 1, -1, -1): + d_str = (today - datetime.timedelta(days=offset)).strftime("%Y-%m-%d") + daily.append( + DailyStat( + date=d_str, + minutes=daily_min.get(d_str, 0), + sprints=daily_sprints.get(d_str, 0), + ) + ) + + return AnalyticsSummary( + completed_sprints=completed_count, + attempted_sprints=attempted_count, + aborted_sprints=aborted_count, + completion_rate=completion_rate, + total_minutes=total_minutes, + total_hours=total_minutes / 60.0, + total_blocked=total_blocked, + active_streak_days=streak, + daily=daily, + ) + + def export_json_string( + self, + days: int = 7, + now: datetime.datetime | None = None, + ) -> str: + ref = now or datetime.datetime.now(datetime.timezone.utc) + sessions = self.load_sessions() + summary = self.compute_analytics(days=days, now=ref) + payload = { + "generated_at": format_rfc3339_utc(ref), + "summary": summary.to_dict(), + "sessions": [s.to_dict() for s in sessions], + } + return json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + + def export_csv_string(self) -> str: + sessions = sorted(self.load_sessions(), key=lambda r: r.start_time) + buf = io.StringIO() + writer = csv.writer(buf, lineterminator="\n") + writer.writerow( + [ + "id", + "profile", + "start_time", + "end_time", + "duration_minutes", + "planned_minutes", + "completed", + "status", + "blocked_count", + ] + ) + for rec in sessions: + status = rec.status or ("completed" if rec.completed else "aborted") + writer.writerow( + [ + rec.id, + rec.profile, + rec.start_time, + rec.end_time, + rec.duration_minutes, + rec.planned_minutes, + str(rec.completed).lower(), + status, + rec.blocked_count, + ] + ) + return buf.getvalue() + + def export_to_file( + self, + out_path: str, + fmt: str = "json", + days: int = 7, + now: datetime.datetime | None = None, + ) -> str: + clean_path = os.path.abspath(out_path) + os.makedirs(os.path.dirname(clean_path) or ".", exist_ok=True) + fmt_lower = fmt.strip().lower() + if fmt_lower == "json": + content = self.export_json_string(days=days, now=now) + elif fmt_lower == "csv": + content = self.export_csv_string() + else: + raise ValueError(f"unsupported export format: {fmt}") + with open(clean_path, "w", encoding="utf-8", newline="") as f: + f.write(content) + return clean_path diff --git a/focusflow_core/supervisor.py b/focusflow_core/supervisor.py new file mode 100644 index 0000000..f49f21b --- /dev/null +++ b/focusflow_core/supervisor.py @@ -0,0 +1,335 @@ +"""Zero-dependency Win32 (Toolhelp32 ctypes) & POSIX (/proc + ps) process supervisor.""" + +from __future__ import annotations + +import ctypes +import errno +import os +import signal +import subprocess +import sys +from typing import Callable + +from .sanitize import is_protected_process + +TH32CS_SNAPPROCESS = 0x00000002 +PROCESS_TERMINATE = 0x00000001 +PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000 +STILL_ACTIVE = 259 +ERROR_ACCESS_DENIED = 5 + +HARDCORE_ANTICHEAT_BINARIES: tuple[str, ...] = ( + "taskmgr.exe", + "processhacker.exe", + "SystemInformer.exe", + "procmon.exe", + "procmon64.exe", + "procexp.exe", + "procexp64.exe", +) + +if sys.platform == "win32": + from ctypes import wintypes + + INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value + + class PROCESSENTRY32W(ctypes.Structure): + _fields_ = [ + ("dwSize", wintypes.DWORD), + ("cntUsage", wintypes.DWORD), + ("th32ProcessID", wintypes.DWORD), + ("th32DefaultHeapID", ctypes.c_size_t), + ("th32ModuleID", wintypes.DWORD), + ("cntThreads", wintypes.DWORD), + ("th32ParentProcessID", wintypes.DWORD), + ("pcPriClassBase", wintypes.LONG), + ("dwFlags", wintypes.DWORD), + ("szExeFile", wintypes.WCHAR * 260), + ] + + _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + + _kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD] + _kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE + + _kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)] + _kernel32.Process32FirstW.restype = wintypes.BOOL + + _kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)] + _kernel32.Process32NextW.restype = wintypes.BOOL + + _kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + _kernel32.OpenProcess.restype = wintypes.HANDLE + + _kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT] + _kernel32.TerminateProcess.restype = wintypes.BOOL + + _kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + _kernel32.GetExitCodeProcess.restype = wintypes.BOOL + + _kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + _kernel32.CloseHandle.restype = wintypes.BOOL + + +def is_protected_pid(pid: int) -> bool: + """Never allow terminating kernel/init PIDs (<= 4), current PID, or parent PID.""" + if pid <= 4: + return True + if pid == os.getpid() or pid == os.getppid(): + return True + return False + + +def is_pid_alive(pid: int) -> bool: + """Return True if a process with `pid` is currently running.""" + if pid <= 0: + return False + if pid == os.getpid(): + return True + + if sys.platform == "win32": + from ctypes import wintypes + + handle = _kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if not handle: + return ctypes.get_last_error() == ERROR_ACCESS_DENIED + try: + exit_code = wintypes.DWORD(0) + if not _kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): + return False + return exit_code.value == STILL_ACTIVE + finally: + _kernel32.CloseHandle(handle) + + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError as exc: + return exc.errno == errno.EPERM + + +def _clean_basename(path_or_name: str) -> str: + s = path_or_name.strip() + if not s: + return "" + return s.replace("\\", "/").rsplit("/", 1)[-1] + + +def resolve_procfs_names(proc_root: str, pid_str: str) -> list[str]: + """Resolve candidate executable names from /proc/, handling 15-byte comm truncation.""" + candidates: list[str] = [] + pid_dir = os.path.join(proc_root, pid_str) + comm_name = "" + + try: + with open(os.path.join(pid_dir, "comm"), "r", encoding="utf-8", errors="replace") as f: + comm_name = f.read().strip() + if comm_name: + candidates.append(comm_name) + except OSError: + pass + + if not comm_name or len(comm_name) >= 15: + try: + exe_target = os.readlink(os.path.join(pid_dir, "exe")) + if exe_target.endswith(" (deleted)"): + exe_target = exe_target[: -len(" (deleted)")] + base = _clean_basename(exe_target) + if base: + candidates.append(base) + except OSError: + pass + + try: + with open(os.path.join(pid_dir, "cmdline"), "rb") as f: + raw_cmd = f.read(4096) + if raw_cmd: + argv0 = raw_cmd.split(b"\x00", 1)[0].decode("utf-8", errors="replace").strip() + base = _clean_basename(argv0) + if base: + candidates.append(base) + except OSError: + pass + + return candidates + + +def enumerate_processes_win32() -> list[tuple[int, list[str]]]: + """Enumerate live Windows processes natively via CreateToolhelp32Snapshot (zero psutil).""" + results: list[tuple[int, list[str]]] = [] + snap = _kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) + if not snap or snap == INVALID_HANDLE_VALUE: + return results + + try: + entry = PROCESSENTRY32W() + entry.dwSize = ctypes.sizeof(PROCESSENTRY32W) + if not _kernel32.Process32FirstW(snap, ctypes.byref(entry)): + return results + + while True: + pid = int(entry.th32ProcessID) + exe_name = str(entry.szExeFile) + if exe_name: + results.append((pid, [exe_name])) + if not _kernel32.Process32NextW(snap, ctypes.byref(entry)): + break + finally: + _kernel32.CloseHandle(snap) + + return results + + +def terminate_pid_win32(pid: int) -> bool: + """Terminate a Windows process by PID via OpenProcess + TerminateProcess.""" + if is_protected_pid(pid): + return False + handle = _kernel32.OpenProcess(PROCESS_TERMINATE, False, pid) + if not handle: + return False + try: + return bool(_kernel32.TerminateProcess(handle, 1)) + finally: + _kernel32.CloseHandle(handle) + + +def enumerate_processes_posix(proc_root: str = "/proc") -> list[tuple[int, list[str]]]: + """Enumerate POSIX processes via /proc (without spawning ps) or fall back to ps on macOS/BSD.""" + results: list[tuple[int, list[str]]] = [] + if os.path.isdir(proc_root): + try: + entries = os.listdir(proc_root) + except OSError: + entries = [] + + saw_pid = False + for name in entries: + if not name.isdigit(): + continue + saw_pid = True + pid = int(name) + cands = resolve_procfs_names(proc_root, name) + if cands: + results.append((pid, cands)) + if saw_pid: + return results + + try: + proc = subprocess.run( + ["ps", "-A", "-o", "pid=,comm="], + capture_output=True, + text=True, + timeout=5, + check=False, + ) + if proc.returncode == 0: + for line in proc.stdout.splitlines(): + parts = line.strip().split(None, 1) + if len(parts) < 2 or not parts[0].isdigit(): + continue + pid = int(parts[0]) + comm = _clean_basename(parts[1]) + if comm: + results.append((pid, [comm])) + except Exception: + pass + + return results + + +def terminate_pid_posix(pid: int) -> bool: + if is_protected_pid(pid): + return False + try: + os.kill(pid, signal.SIGTERM) + return True + except OSError: + return False + + +class ProcessSupervisor: + """Cross-platform zero-dependency process supervisor with strict system/host denylist.""" + + def __init__( + self, + blocked: list[str] | tuple[str, ...] | None = None, + enumerator: Callable[[], list[tuple[int, list[str]]]] | None = None, + terminator: Callable[[int], bool] | None = None, + ) -> None: + self.blocked_names: set[str] = set() + for raw in blocked or (): + if not isinstance(raw, str): + continue + cleaned = _clean_basename(raw).lower() + if not cleaned or is_protected_process(cleaned): + continue + self.blocked_names.add(cleaned) + if cleaned.endswith(".exe"): + base = cleaned[:-4] + if base and not is_protected_process(base): + self.blocked_names.add(base) + else: + with_exe = f"{cleaned}.exe" + if not is_protected_process(with_exe): + self.blocked_names.add(with_exe) + + if enumerator is not None: + self._enumerator = enumerator + elif sys.platform == "win32": + self._enumerator = enumerate_processes_win32 + else: + self._enumerator = enumerate_processes_posix + + if terminator is not None: + self._terminator = terminator + elif sys.platform == "win32": + self._terminator = terminate_pid_win32 + else: + self._terminator = terminate_pid_posix + + def should_terminate(self, pid: int, candidate_names: list[str] | tuple[str, ...]) -> str | None: + """Return matched executable name if process should be terminated, else None.""" + if is_protected_pid(pid) or not self.blocked_names: + return None + + for cand in candidate_names: + base = _clean_basename(cand) + if base and is_protected_process(base): + return None + + for cand in candidate_names: + base = _clean_basename(cand) + if base and base.lower() in self.blocked_names: + return base + + return None + + def scan_and_terminate(self) -> list[str]: + """Scan active OS processes and terminate matching non-protected targets.""" + if not self.blocked_names: + return [] + + terminated: list[str] = [] + for pid, candidates in self._enumerator(): + matched = self.should_terminate(pid, candidates) + if matched is not None and self._terminator(pid): + terminated.append(f"{matched} (PID: {pid})") + return terminated + + +class AntiCheatGuard: + """Hardcore task-killer / process-inspector suppression guard.""" + + def __init__(self, strictness: str = "standard") -> None: + self.strictness = strictness.strip().lower() + targets = list(HARDCORE_ANTICHEAT_BINARIES) if self.strictness == "hardcore" else [] + self.supervisor = ProcessSupervisor(targets) + + def enforce(self) -> list[str]: + if self.strictness == "hardcore": + return self.supervisor.scan_and_terminate() + return [] diff --git a/focusflow_core/timer.py b/focusflow_core/timer.py new file mode 100644 index 0000000..9d73e9b --- /dev/null +++ b/focusflow_core/timer.py @@ -0,0 +1,104 @@ +"""Zero-drift monotonic deadline timer and non-pasteable Friction Challenge generator.""" + +from __future__ import annotations + +import math +import secrets +import time +from typing import Callable + +# Unambiguous uppercase alphanumeric characters (excludes 0, O, 1, I) +FRICTION_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + + +def generate_friction_token(length: int = 16) -> str: + """Generate a cryptographically random high-friction challenge string.""" + if length < 8: + length = 8 + return "".join(secrets.choice(FRICTION_ALPHABET) for _ in range(length)) + + +class MonotonicPhaseTimer: + """Drift-free phase countdown timer powered by `time.monotonic()`. + + Holds safely at expiration (`awaiting_transition=True`) so modal dialogs + never burn break or work time in the background before the user acknowledges them. + """ + + def __init__(self, clock_fn: Callable[[], float] = time.monotonic) -> None: + self._clock = clock_fn + self.is_running: bool = False + self.is_paused: bool = False + self.awaiting_transition: bool = False + self.phase: str = "WORK" + self.total_seconds: float = 0.0 + self._started_monotonic: float = 0.0 + self._deadline: float = 0.0 + self._paused_remaining: float = 0.0 + + def start(self, duration_seconds: float, phase: str = "WORK") -> None: + dur = max(0.0, float(duration_seconds)) + now = self._clock() + self.phase = phase + self.total_seconds = dur + self._started_monotonic = now + self._deadline = now + dur + self._paused_remaining = dur + self.is_running = True + self.is_paused = False + self.awaiting_transition = False + + def stop(self) -> None: + self.is_running = False + self.is_paused = False + self.awaiting_transition = False + self._deadline = 0.0 + self._paused_remaining = 0.0 + self.total_seconds = 0.0 + + def pause(self) -> None: + if not self.is_running or self.is_paused or self.awaiting_transition: + return + self._paused_remaining = max(0.0, self._deadline - self._clock()) + self.is_paused = True + + def resume(self) -> None: + if not self.is_running or not self.is_paused or self.awaiting_transition: + return + self._deadline = self._clock() + self._paused_remaining + self.is_paused = False + + def remaining_seconds_float(self) -> float: + if not self.is_running or self.awaiting_transition: + return 0.0 + if self.is_paused: + return max(0.0, self._paused_remaining) + return max(0.0, self._deadline - self._clock()) + + def remaining_seconds(self) -> int: + rem = self.remaining_seconds_float() + return int(math.ceil(rem)) if rem > 0 else 0 + + def elapsed_seconds(self) -> int: + if self.total_seconds <= 0: + return 0 + rem = self.remaining_seconds_float() + return max(0, int(round(self.total_seconds - rem))) + + def progress_ratio(self) -> float: + if self.total_seconds <= 0: + return 0.0 + return max(0.0, min(1.0, self.remaining_seconds_float() / self.total_seconds)) + + def poll_expired(self) -> bool: + """Return True exactly once when the active phase reaches its deadline. + + Transitions into `awaiting_transition=True` so repeated ticks while a modal + dialog is open never queue duplicate expiration callbacks or burn the next phase. + """ + if not self.is_running or self.is_paused or self.awaiting_transition: + return False + if self._clock() >= self._deadline: + self.awaiting_transition = True + return True + return False diff --git a/legacy/FocusFlowV1.py b/legacy/FocusFlowV1.py deleted file mode 100644 index 7b1e6ae..0000000 --- a/legacy/FocusFlowV1.py +++ /dev/null @@ -1,998 +0,0 @@ -import tkinter as tk -from tkinter import messagebox, ttk, simpledialog -import psutil -import os -import sys -import datetime -import time -import threading -import json -import random -import string -import hashlib -import http.server -import socketserver -import winreg -import logging -import subprocess -import webbrowser -import pyautogui -import ctypes -import urllib.parse -from threading import Lock -from queue import Queue - -# --- KÜTÜPHANE KONTROLÜ (Resim Çıktısı İçin) --- -try: - from PIL import Image, ImageDraw, ImageFont - HAS_PIL = True -except ImportError: - HAS_PIL = False - -# --- AYARLAR --- -pyautogui.FAILSAFE = False - -# --- LOGLAMA --- -logging.basicConfig(filename='focusflow_log.txt', level=logging.ERROR, - format='%(asctime)s - %(levelname)s - %(message)s') - -# --- SABİTLER --- -HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts" -REDIRECT_IP = "127.0.0.1" -SETTINGS_FILE = "focusflow_settings.json" -APP_NAME = "FocusFlowService" -MOTIVATION_URL = "http://127.0.0.1:8080" - -# --- MODERN RENK PALETİ --- -COLOR_BG = "#1e1e2e" -COLOR_CARD = "#313244" -COLOR_TEXT = "#cdd6f4" -COLOR_PRIMARY = "#a6e3a1" -COLOR_SECONDARY = "#89b4fa" -COLOR_WARNING = "#f9e2af" -COLOR_DANGER = "#f38ba8" -COLOR_ACCENT = "#cba6f7" -COLOR_SUCCESS = COLOR_PRIMARY -COLOR_LIGHT = "#ffffff" - -DEFAULT_QUOTES = [ - "Muhtaç olduğun kudret, damarlarındaki asil kanda mevcuttur!", - "Başarı, disiplinin eseridir.", - "Şu an rakibin çalışıyor, sen ne yapıyorsun?", - "Acı geçici, gurur kalıcıdır.", - "Disiplin, motivasyonu her zaman yener.", - "Her dakika değerlidir, boşa harcama!", - "Hedefine odaklan, engellerden güçlenerek geç!", - "Yarın deme, yarınlar bitmez.", - "Başlamak için mükemmel olmak zorunda değilsin, ama mükemmel olmak için başlamak zorundasın.", - "Hayallerin, mazeretlerinden büyük olmalı.", - "Zor, imkansız demek değildir.", - "Terlemeden kazanılan zaferin tadı olmaz.", - "Bugün yaptığın fedakarlıklar, yarınki gülüşlerin olacak.", - "Vazgeçmek, korkakların işidir.", - "Zirve, kalabalık değildir.", - "Kendine bir söz ver ve onu tut.", - "Yorgunluk sadece zihindedir, bedenin daha fazlasını yapabilir.", - "Şikayet etme, daha çok çalış.", - "En iyi intikam, devasa bir başarıdır.", - "Karanlık olmadan yıldızları göremezsin.", - "Limitlerini zorla, çünkü limit yok.", - "Sadece inanmak yetmez, ter dökmelisin.", - "Uykun geliyorsa yüzünü yıka, hayallerin uyumuyor.", - "Bir saatlik çalışma, bir ömürlük pişmanlığı önler.", - "Kaybetmekten korkma, denememekten kork.", - "Odaklanmak, hayır diyebilmektir.", - "Senin potansiyelin, tahmin ettiğinden çok daha fazla.", - "Bugün ektiğini, yarın biçeceksin.", - "Zaman en değerli sermayendir, iflas etme.", - "Rahatlık bölgesi, hayallerin öldüğü yerdir.", - "Bir gün değil, birinci gün.", - "Büyük hayaller, büyük bedeller ister.", - "Sızlanma, çalış. Hayat sızlananları beklemez.", - "Gelecekteki sen, şu an yaptıkların için sana teşekkür edecek mi?", - "Durdurulamaz ol.", - "Başarı tesadüf değildir.", - "Eğer kolay olsaydı, herkes yapardı.", - "Seni öldürmeyen şey, başarıya götürür.", - "Kendi hikayenin kahramanı ol.", - "Bugün çalışmazsan, yarın başkası senin yerine kazanır.", - "Disiplin özgürlüktür.", - "Motivasyon başlar, alışkanlık devam ettirir.", - "Düşmek sorun değil, kalkmamak sorundur.", - "Yolun sonunu değil, attığın adımı düşün.", - "Odaklan, üret, başar.", - "Telefonu bırak, kalemine sarıl.", - "Beynin bir kas, onu çalıştır.", - "Zaman akıyor, sen durma.", - "Mazeretler sadece kaybedenler içindir.", - "Asla pes etme. Asla.", - "Kendini kandırma, o masaya otur.", - "Başarı, sessizce çalışmaktır.", - "Gürültüyü görmezden gel, hedefe kilitlen.", - "Yetenek çalışmazsa, çalışma yeteneği yener.", - "Bugünün acısı, yarının gücüdür.", - "Hedefin güneş olsun, ıskalarsan yıldızlara ulaşırsın.", - "Çalışmak, en asil eylemdir.", - "Geleceğini, şu an inşa ediyorsun.", - "Zihnin efendisi ol, kölesi değil.", - "Bahaneler seni bir yere götürmez.", - "Şampiyonlar salonda değil, zihinde doğar.", - "Sabır ve ter, başarının formülüdür.", - "Yol yokuşsa, zirveye yaklaşıyorsun demektir.", - "Kendi şansını kendin yarat.", - "Durma, nefes al ve devam et.", - "Başarmak zorundasın, başka seçeneğin yok.", - "Hayat, cesurları sever.", - "Odaklanmış bir zihin, en güçlü silahtır.", - "Sadece yap.", - "Bekleme, zaman asla 'tam doğru' olmayacak.", - "Küçük adımlar, büyük mesafeler kat ettirir.", - "Kendine inan, dünya inansa ne yazar?", - "Çalış, kazan, tekrarla.", - "Boş zaman yoktur, boşa geçen zaman vardır.", - "Disiplin, anlık hazzı reddetmektir.", - "İrade, kas gibidir; kullandıkça güçlenir.", - "Zorluklar, karakterini ortaya çıkarır.", - "Daha iyisini yapabilirsin.", - "Bugün kendine bir iyilik yap ve çalış.", - "Hayallerine giden yol, konfor alanından geçmez.", - "Başarı detaylarda gizlidir.", - "Sıradan olma, efsane ol.", - "Yapabileceğine inanırsan, yolun yarısını gitmişsindir.", - "Erteleme, hayatını çalmasına izin verme.", - "En büyük rakibin, aynadaki kişi.", - "Zafer, vazgeçmeyenlerindir.", - "Korkularının üzerine git.", - "Büyük düşün, büyük yaşa.", - "Her saniye yeni bir fırsattır.", - "Zihinsel dayanıklılık, fiziksel güçten üstündür.", - "Çalışmadan dua etmek, biletsiz piyango beklemektir.", - "O masadan kalkma.", - "Bildirimleri kapat, beynini aç.", - "Yarı yolda bırakma.", - "Kendine saygı duy ve çalış.", - "Başarı bedel ister, ödemeye hazır mısın?", - "Hayat kısa, izin bırak.", - "Odaklan. Sadece odaklan.", - "Yapabilirsin. Yapacaksın." -] - -# --- HTML ŞABLONU --- -def get_html_content(violation_count, quotes): - quote = random.choice(quotes) if quotes else "Odaklan ve başar!" - return f""" - ODAKLAN! - -
⛔
-

YASAKLI BÖLGE!

-
"{quote}"
-
İhlal Sayısı: {violation_count}
- - """ - -# --- GLOBAL DEĞİŞKENLER --- -violation_counter = 0 -violation_lock = Lock() -server_port = 8080 - -def increment_violation(): - global violation_counter - with violation_lock: - violation_counter += 1 - return violation_counter - -def get_active_window_info(): - try: - hwnd = ctypes.windll.user32.GetForegroundWindow() - length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) - buff = ctypes.create_unicode_buffer(length + 1) - ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) - title = buff.value.lower() - pid = ctypes.c_ulong() - ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) - process_name = psutil.Process(pid.value).name().lower() - return title, process_name - except: return "", "" - -# --- AKILLI MASAÜSTÜ BULUCU (OneDrive Çözümü) --- -def get_desktop_path(): - user_home = os.path.expanduser("~") - possible_paths = [ - os.path.join(user_home, "Desktop"), - os.path.join(user_home, "OneDrive", "Desktop"), - os.path.join(user_home, "OneDrive", "Masaüstü"), - os.path.join(user_home, "Masaüstü") - ] - for path in possible_paths: - if os.path.exists(path): - return path - return user_home - -# --- SUNUCU --- -class MotivationHandler(http.server.BaseHTTPRequestHandler): - quotes = DEFAULT_QUOTES - def do_GET(self): - self.send_response(200) - self.send_header("Content-type", "text/html; charset=utf-8") - self.end_headers() - self.wfile.write(get_html_content(violation_counter, MotivationHandler.quotes).encode('utf-8')) - def log_message(self, format, *args): return - -def start_server(): - global server_port - while True: - try: socketserver.TCPServer(("", server_port), MotivationHandler).serve_forever(); break - except: server_port += 1 - -# --- HOSTS --- -class HostsManager: - _lock = Lock() - @staticmethod - def clean_hosts(): - with HostsManager._lock: - try: - if not os.access(HOSTS_PATH, os.W_OK): return - with open(HOSTS_PATH, 'r') as f: lines = f.readlines() - new_lines = [l for l in lines if "# --- FOCUSFLOW" not in l and REDIRECT_IP not in l] - with open(HOSTS_PATH, 'w') as f: f.writelines(new_lines) - try: subprocess.run(["ipconfig", "/flushdns"], shell=True, stdout=subprocess.DEVNULL) - except: pass - except: pass - @staticmethod - def write_blocks(sites): - # Sadece domain olanları (nokta içerenleri) hosts'a yaz - domain_sites = [s for s in sites if "." in s] - HostsManager.clean_hosts() - if not domain_sites: return - with HostsManager._lock: - try: - with open(HOSTS_PATH, 'a') as f: - f.write("\n# --- FOCUSFLOW BLOCK START ---\n") - for s in domain_sites: f.write(f"{REDIRECT_IP} {s}\n{REDIRECT_IP} www.{s}\n") - f.write("# --- FOCUSFLOW BLOCK END ---\n") - try: subprocess.run(["ipconfig", "/flushdns"], shell=True, stdout=subprocess.DEVNULL) - except: pass - except: pass - -# --- GRAFİK ÇİZİCİ --- -class SimpleGraph(tk.Canvas): - def __init__(self, parent, data_dict, width=550, height=180, bg=COLOR_CARD): - super().__init__(parent, width=width, height=height, bg=bg, highlightthickness=0) - self.data = data_dict - self.draw_graph() - - def draw_graph(self): - self.delete("all") - if not self.data: - self.create_text(275, 90, text="Henüz Veri Yok", fill=COLOR_TEXT, font=("Segoe UI", 12)) - return - - dates = sorted(list(self.data.keys()))[-7:] # Son 7 gün - values = [self.data[d] for d in dates] - if not values: return - - max_val = max(values) if max(values) > 0 else 1 - bar_width = 40 - spacing = 30 - start_x = 40 - base_y = 150 - - self.create_text(275, 15, text="Haftalık Çalışma Süresi (Dakika)", fill=COLOR_TEXT, font=("Segoe UI", 10, "bold")) - - for i, (date_str, val) in enumerate(zip(dates, values)): - x0 = start_x + i * (bar_width + spacing) - bar_height = (val / max_val) * 100 - y0 = base_y - bar_height - x1 = x0 + bar_width - y1 = base_y - - color = COLOR_PRIMARY if val >= 60 else COLOR_SECONDARY - self.create_rectangle(x0, y0, x1, y1, fill=color, outline="") - self.create_text((x0+x1)/2, y0-10, text=str(val), fill=COLOR_TEXT, font=("Segoe UI", 9)) - - try: d_lbl = datetime.datetime.strptime(date_str, "%Y-%m-%d").strftime("%d/%m") - except: d_lbl = date_str - self.create_text((x0+x1)/2, y1+15, text=d_lbl, fill=COLOR_TEXT, font=("Segoe UI", 8)) - -# --- ANA UYGULAMA --- -class FocusFlow: - def __init__(self, root): - self.root = root - self.root.title("FocusFlow") - self.root.geometry("900x900") - self.root.configure(bg=COLOR_BG) - - self.setup_styles() - self.settings = self.load_settings() - self.is_locked = False - self.lock_hash = "" - self.pomodoro_state = self.settings.get("pomodoro_state", "WORK") - self.current_task_name = "" - - # --- MOTİVASYON SÖZLERİNİ GÜNCELLEME DEDEKTİFİ --- - # Eğer kayıtlı sözler azsa (eski sürümse) yenileriyle değiştir - saved_quotes = self.settings.get("motivation_quotes", []) - if len(saved_quotes) < 50: - self.motivation_quotes = DEFAULT_QUOTES.copy() - self.settings["motivation_quotes"] = self.motivation_quotes - self.save_settings() - else: - self.motivation_quotes = saved_quotes - - MotivationHandler.quotes = self.motivation_quotes - # ------------------------------------------------ - - self.gui_queue = Queue() - self.calculate_streak() - HostsManager.clean_hosts() - self.add_to_startup() - self.setup_ui() - - threading.Thread(target=self.daemon_loop, daemon=True).start() - threading.Thread(target=start_server, daemon=True).start() - - self.process_gui_queue() - self.update_stats_display() - root.protocol("WM_DELETE_WINDOW", self.on_close) - - def setup_styles(self): - style = ttk.Style() - style.theme_use('clam') - style.configure('TFrame', background=COLOR_BG) - style.configure('TLabel', background=COLOR_BG, foreground=COLOR_TEXT, font=('Segoe UI', 10)) - style.configure('Card.TFrame', background=COLOR_CARD, relief='flat') - style.configure('TNotebook', background=COLOR_BG, borderwidth=0) - style.configure('TNotebook.Tab', background=COLOR_CARD, foreground=COLOR_TEXT, padding=[15, 8], font=('Segoe UI', 10, 'bold'), borderwidth=0) - style.map('TNotebook.Tab', background=[('selected', COLOR_PRIMARY)], foreground=[('selected', '#000000')]) - style.configure('TLabelframe', background=COLOR_BG, foreground=COLOR_ACCENT, borderwidth=1, relief='solid') - style.configure('TLabelframe.Label', background=COLOR_BG, foreground=COLOR_ACCENT, font=('Segoe UI', 11, 'bold')) - style.configure('TRadiobutton', background=COLOR_BG, foreground=COLOR_TEXT, font=('Segoe UI', 10)) - style.map('TRadiobutton', background=[('active', COLOR_BG)]) - style.configure('TCheckbutton', background=COLOR_BG, foreground=COLOR_TEXT, font=('Segoe UI', 10)) - style.map('TCheckbutton', background=[('active', COLOR_BG)]) - style.configure("Treeview", background=COLOR_CARD, foreground=COLOR_TEXT, fieldbackground=COLOR_CARD, borderwidth=0, font=('Segoe UI', 10)) - style.configure("Treeview.Heading", background=COLOR_SECONDARY, foreground="white", font=('Segoe UI', 10, 'bold')) - style.map("Treeview", background=[('selected', COLOR_PRIMARY)], foreground=[('selected', 'black')]) - - def load_settings(self): - today = datetime.date.today().strftime("%Y-%m-%d") - default = { - "sites": [], "apps": [], "whitelist_sites": [], "phone": "", - "mode": "standard", "duration": 60, - "pomo_work": 25, "pomo_break": 5, - "flex_break": 15, "start_time_str": "09:00", "end_time_str": "20:00", "flex_strict": True, - "stats": {"total_sessions": 0, "total_minutes": 0, "total_violations": 0}, - "history": {today: 0}, - "session_log": [], - "streak": 0, "last_session_date": "", - "filter_mode": "blacklist", - "is_locked": False, "lock_hash": "", "end_timestamp": 0, "pomodoro_state": "WORK", - "motivation_quotes": DEFAULT_QUOTES.copy(), "whatsapp_enabled": True, - "work_start_timestamp": 0, "flex_end_timestamp": 0, "pomo_cycles": 4 - } - if os.path.exists(SETTINGS_FILE): - try: - with open(SETTINGS_FILE, "r", encoding="utf-8") as f: - saved = json.load(f) - default.update(saved) - if "session_log" not in default: default["session_log"] = [] - return default - except: return default - return default - - def save_settings(self): - try: - with open(SETTINGS_FILE, "w", encoding="utf-8") as f: json.dump(self.settings, f, indent=2, ensure_ascii=False) - except: pass - - def calculate_streak(self): - today = datetime.date.today() - last_date_str = self.settings.get("last_session_date", "") - if last_date_str: - try: - last_date = datetime.datetime.strptime(last_date_str, "%Y-%m-%d").date() - diff = (today - last_date).days - if diff > 1: self.settings["streak"] = 0 - except: self.settings["streak"] = 0 - self.save_settings() - - def add_to_startup(self): - try: - key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_ALL_ACCESS) - script = os.path.abspath(sys.argv[0]) - python_path = sys.executable.replace("python.exe", "pythonw.exe") if sys.executable.endswith("python.exe") else sys.executable - winreg.SetValueEx(key, APP_NAME, 0, winreg.REG_SZ, f'"{python_path}" "{script}"') - winreg.CloseKey(key) - except: pass - - def create_modern_button(self, parent, text, command, color, width=20, state="normal"): - return tk.Button(parent, text=text, command=command, bg=color, fg="#ffffff", - font=("Segoe UI", 11, "bold"), relief="flat", - activebackground=color, activeforeground="#eeeeee", - cursor="hand2", width=width, state=state, pady=8) - - # --- ARAYÜZ --- - def setup_ui(self): - self.notebook = ttk.Notebook(self.root) - self.notebook.pack(pady=20, fill='both', expand=True, padx=20) - - self.tab_home = ttk.Frame(self.notebook); self.notebook.add(self.tab_home, text='🏠 Ana Sayfa') - self.tab_sites = ttk.Frame(self.notebook); self.notebook.add(self.tab_sites, text='🌐 Siteler') - self.tab_apps = ttk.Frame(self.notebook); self.notebook.add(self.tab_apps, text='💻 Uygulamalar') - self.tab_motivation = ttk.Frame(self.notebook); self.notebook.add(self.tab_motivation, text='💪 Motivasyon') - self.tab_stats = ttk.Frame(self.notebook); self.notebook.add(self.tab_stats, text='📊 İstatistikler') - self.tab_set = ttk.Frame(self.notebook); self.notebook.add(self.tab_set, text='⚙️ Ayarlar') - - self.setup_home() - self.setup_lists(self.tab_sites, "sites", "Web Sitesi (youtube.com)") - self.setup_lists(self.tab_apps, "apps", "Uygulama (steam.exe)") - self.setup_motivation() - self.setup_stats() - self.setup_settings() - - def setup_home(self): - f = self.tab_home - - header_frame = tk.Frame(f, bg=COLOR_BG) - header_frame.pack(fill='x', pady=10) - tk.Label(header_frame, text="⚡ FocusFlow", font=("Segoe UI", 36, "bold"), fg=COLOR_PRIMARY, bg=COLOR_BG).pack() - - streak_val = self.settings.get("streak", 0) - tk.Label(header_frame, text=f"🔥 {streak_val} Günlük Seri", font=("Segoe UI", 14, "bold"), fg="#ff9f43", bg=COLOR_BG).pack() - - self.mode_var = tk.StringVar(value=self.settings["mode"]) - fr = ttk.LabelFrame(f, text="Çalışma Modu") - fr.pack(pady=10, fill="x", padx=40) - ttk.Radiobutton(fr, text="⏱️ Standart Mod", variable=self.mode_var, value="standard", command=self.toggle_mode_ui).pack(side="left", padx=20, pady=10) - ttk.Radiobutton(fr, text="🍅 Detaylı Zamanlayıcı", variable=self.mode_var, value="pomodoro", command=self.toggle_mode_ui).pack(side="left", padx=20, pady=10) - ttk.Radiobutton(fr, text="📅 Esnek Mod", variable=self.mode_var, value="flex", command=self.toggle_mode_ui).pack(side="left", padx=20, pady=10) - - self.frm_time = ttk.LabelFrame(f, text="Zaman Ayarları") - self.frm_time.pack(pady=5, fill="x", padx=40) - - self.lbl_std = ttk.Label(self.frm_time, text="Süre (dk):"); self.spin_std = ttk.Spinbox(self.frm_time, from_=1, to=600, width=10); self.spin_std.set(self.settings["duration"]) - self.lbl_p_w = ttk.Label(self.frm_time, text="Ders (dk):"); self.spin_p_w = ttk.Spinbox(self.frm_time, from_=1, to=120, width=8); self.spin_p_w.set(self.settings["pomo_work"]) - self.lbl_p_b = ttk.Label(self.frm_time, text="Mola (dk):"); self.spin_p_b = ttk.Spinbox(self.frm_time, from_=1, to=6, width=8); self.spin_p_b.set(self.settings["pomo_break"]) - self.lbl_cycles = ttk.Label(self.frm_time, text="Tekrar Sayısı:"); self.spin_cycles = ttk.Spinbox(self.frm_time, from_=1, to=20, width=8); self.spin_cycles.set(self.settings.get("pomo_cycles", 4)) - self.lbl_flex_start = ttk.Label(self.frm_time, text="Başlangıç (SS:DD):"); self.ent_flex_start = ttk.Entry(self.frm_time, width=8); self.ent_flex_start.insert(0, datetime.datetime.now().strftime("%H:%M")) - self.lbl_flex_end = ttk.Label(self.frm_time, text="Bitiş (SS:DD):"); self.ent_flex_end = ttk.Entry(self.frm_time, width=8); self.ent_flex_end.insert(0, self.settings.get("end_time_str", "20:00")) - self.lbl_flex_break = ttk.Label(self.frm_time, text="Mola Süresi (dk):"); self.spin_flex_break = ttk.Spinbox(self.frm_time, from_=5, to=60, width=8); self.spin_flex_break.set(self.settings.get("flex_break", 15)) - self.var_flex_strict = tk.BooleanVar(value=self.settings.get("flex_strict", True)) - self.chk_flex_strict = tk.Checkbutton(self.frm_time, text="⚠️ 40 dk Kuralı Olsun", variable=self.var_flex_strict, bg=COLOR_BG) - - btn_frame = tk.Frame(f, bg=COLOR_BG); btn_frame.pack(pady=10) - self.btn_start = self.create_modern_button(btn_frame, "🔒 PLANI BAŞLAT", self.start_lock, COLOR_PRIMARY, width=25) - self.btn_start.pack(pady=5) - - self.btn_break = self.create_modern_button(btn_frame, "☕ MOLA VER", self.take_manual_break, COLOR_WARNING, width=25, state="disabled") - - self.btn_emerg = tk.Button(btn_frame, text="🆘 ACİL DURUM KODU", command=self.emergency_unlock, bg=COLOR_DANGER, fg="white", font=("Segoe UI", 9), relief="flat", state="disabled"); self.btn_emerg.pack(pady=5) - self.lbl_status = tk.Label(f, text="✅ Sistem Hazır", font=("Segoe UI", 12), bg=COLOR_BG, fg=COLOR_SECONDARY); self.lbl_status.pack(pady=5) - self.toggle_mode_ui() - - def toggle_mode_ui(self): - for w in self.frm_time.winfo_children(): w.grid_forget() - self.btn_break.pack_forget() - if self.mode_var.get()=="standard": - self.lbl_std.grid(row=0,column=0,padx=20,pady=20); self.spin_std.grid(row=0,column=1,padx=10) - elif self.mode_var.get()=="pomodoro": - self.lbl_p_w.grid(row=0,column=0,padx=15,pady=10); self.spin_p_w.grid(row=0,column=1) - self.lbl_p_b.grid(row=0,column=2,padx=15); self.spin_p_b.grid(row=0,column=3) - self.lbl_cycles.grid(row=1,column=0,padx=15,pady=10); self.spin_cycles.grid(row=1,column=1) - else: - self.lbl_flex_start.grid(row=0,column=0,padx=15,pady=10); self.ent_flex_start.grid(row=0,column=1) - self.lbl_flex_end.grid(row=0,column=2,padx=15); self.ent_flex_end.grid(row=0,column=3) - self.lbl_flex_break.grid(row=1,column=0,padx=15,pady=10); self.spin_flex_break.grid(row=1,column=1) - # --- DÜZELTME BURADA: sticky="w" EKLENDİ --- - self.chk_flex_strict.grid(row=1, column=2, columnspan=2, sticky="w", padx=5) - # ------------------------------------------- - self.btn_break.pack(pady=5, after=self.btn_start) - self.settings["mode"] = self.mode_var.get() - - def setup_lists(self, parent, key, title): - tk.Label(parent, text=f"➕ {title}", font=("Segoe UI", 12, "bold"), bg=COLOR_BG, fg=COLOR_ACCENT).pack(pady=15) - input_frame = tk.Frame(parent, bg=COLOR_BG); input_frame.pack(pady=5, padx=40, fill="x") - entry = ttk.Entry(input_frame, font=('Segoe UI', 10)); entry.pack(side=tk.LEFT, fill="x", expand=True, padx=(0, 10)) - lst = tk.Listbox(parent, height=14, font=("Consolas", 10), bg=COLOR_CARD, fg=COLOR_TEXT, selectbackground=COLOR_SECONDARY, borderwidth=0, highlightthickness=0) - - # --- GÜNCELLENEN EKLEME MANTIĞI (URL TEMİZLEYİCİ) --- - def add(): - v = entry.get().strip().lower() - - # Sadece 'sites' kısmındaysak ve içinde nokta (.) varsa URL temizliği yap - if key == "sites" and "." in v: - if v.startswith("http://") or v.startswith("https://"): - try: - v = urllib.parse.urlparse(v).netloc - except: pass - if "/" in v: - v = v.split("/")[0] - - if v and v not in self.settings[key]: - if key=="apps" and not v.endswith(".exe"): v+=".exe" - self.settings[key].append(v); lst.insert(tk.END, v); self.save_settings(); entry.delete(0, tk.END) - # ---------------------------------------------------- - - def rem(): - try: i = lst.curselection()[0]; v = lst.get(i); self.settings[key].remove(v); lst.delete(i); self.save_settings() - except: pass - tk.Button(input_frame, text="Ekle", command=add, bg=COLOR_SUCCESS, fg="white", relief="flat", font=("Segoe UI", 9, "bold"), width=8).pack(side=tk.LEFT, padx=2) - tk.Button(input_frame, text="Sil", command=rem, bg=COLOR_DANGER, fg="white", relief="flat", font=("Segoe UI", 9, "bold"), width=8).pack(side=tk.LEFT, padx=2) - lst.pack(pady=10, fill='both', expand=True, padx=40) - for i in self.settings[key]: lst.insert(tk.END, i) - - def setup_motivation(self): - f = self.tab_motivation - tk.Label(f, text="💪 Motivasyon Sözleri", font=("Segoe UI", 16, "bold"), fg=COLOR_ACCENT, bg=COLOR_BG).pack(pady=20) - l_frame = ttk.Frame(f); l_frame.pack(pady=10, padx=40, fill="both", expand=True) - l = tk.Listbox(l_frame, height=15, font=("Segoe UI", 10), bg=COLOR_CARD, fg=COLOR_TEXT, borderwidth=0, highlightthickness=0); l.pack(fill="both", expand=True, pady=10) - for q in self.motivation_quotes: l.insert("end", q) - bf = tk.Frame(f, bg=COLOR_BG); bf.pack(pady=10) - def add(): - t = simpledialog.askstring("Ekle", "Söz:") - if t: self.motivation_quotes.append(t); self.save_settings(); l.insert("end", t) - def rem(): - try: i=l.curselection()[0]; self.motivation_quotes.pop(i); l.delete(i); self.save_settings() - except: pass - self.create_modern_button(bf, "Ekle", add, COLOR_SUCCESS, width=10).pack(side="left", padx=5) - self.create_modern_button(bf, "Sil", rem, COLOR_DANGER, width=10).pack(side="left", padx=5) - - def setup_stats(self): - tk.Label(self.tab_stats, text="📊 İstatistikler", font=("Segoe UI", 18, "bold"), fg=COLOR_ACCENT, bg=COLOR_BG).pack(pady=10) - self.graph_frame = tk.Frame(self.tab_stats, bg=COLOR_BG); self.graph_frame.pack(pady=5) - self.graph = SimpleGraph(self.graph_frame, self.settings.get("history", {})) - self.graph.pack() - - tk.Label(self.tab_stats, text="📅 Bugünün Kayıtları", font=("Segoe UI", 12, "bold"), fg=COLOR_TEXT, bg=COLOR_BG).pack(pady=(15,5)) - tree_frame = tk.Frame(self.tab_stats) - tree_frame.pack(pady=5, padx=20, fill="x", expand=False) - columns = ("saat", "gorev", "sure") - self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", height=6) - self.tree.heading("saat", text="Saat"); self.tree.column("saat", width=80, anchor="center") - self.tree.heading("gorev", text="Çalışma Konusu"); self.tree.column("gorev", width=250) - self.tree.heading("sure", text="Süre"); self.tree.column("sure", width=80, anchor="center") - scrollbar = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview) - self.tree.configure(yscrollcommand=scrollbar.set) - self.tree.pack(side="left", fill="x", expand=True) - scrollbar.pack(side="right", fill="y") - self.create_modern_button(self.tab_stats, "📄 Rapor Al (.png)", self.export_png_report, COLOR_SECONDARY, width=30).pack(pady=15) - - def update_daily_log_display(self): - for i in self.tree.get_children(): self.tree.delete(i) - today_str = datetime.date.today().strftime("%Y-%m-%d") - logs = self.settings.get("session_log", []) - todays_logs = [log for log in logs if log.get("date") == today_str] - for log in todays_logs: - self.tree.insert("", "end", values=(log.get("time"), log.get("task"), f"{log.get('duration')} dk")) - - def export_png_report(self): - # Eğer Pillow yüklü değilse uyarı ver ve TXT olarak kaydetmeyi teklif et veya otomatik yap - if not HAS_PIL: - if messagebox.askyesno("Eksik Kütüphane", "Resim oluşturmak için 'Pillow' kütüphanesi gerekli.\nYine de Metin (.txt) olarak kaydetmek ister misin?"): - self.export_weekly_report() - return - - logs = self.settings.get("session_log", []) - if not logs: messagebox.showinfo("Bilgi", "Henüz kayıt yok."); return - - try: - # Resim oluşturma (A4 boyutuna yakın veya içerik kadar uzun) - width, height = 800, 1000 - bg_color = (30, 30, 46) # Koyu tema - text_color = (205, 214, 244) - accent_color = (166, 227, 161) # Yeşil - - img = Image.new('RGB', (width, height), color=bg_color) - d = ImageDraw.Draw(img) - - # Font ayarla - try: - # Windows'ta varsa Arial, yoksa default - title_font = ImageFont.truetype("arial.ttf", 40) - header_font = ImageFont.truetype("arial.ttf", 25) - text_font = ImageFont.truetype("arial.ttf", 18) - except: - title_font = ImageFont.load_default() - header_font = ImageFont.load_default() - text_font = ImageFont.load_default() - - # Başlık - d.text((50, 50), "FOCUSFLOW RAPORU", font=title_font, fill=accent_color) - d.text((50, 100), f"Tarih: {datetime.datetime.now().strftime('%d.%m.%Y %H:%M')}", font=text_font, fill=(150, 150, 150)) - - y = 150 - today = datetime.date.today() - logs_by_date = {} - for log in logs: - d_str = log.get("date") - if d_str not in logs_by_date: logs_by_date[d_str] = [] - logs_by_date[d_str].append(log) - - sorted_dates = sorted(logs_by_date.keys(), reverse=True) - - for date_str in sorted_dates: - d_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d").date() - if (today - d_obj).days > 7: continue # Son 7 gün - - total_min = sum(l['duration'] for l in logs_by_date[date_str]) - - # Tarih başlığı arka planı - d.rectangle([(40, y), (760, y+40)], fill=(49, 50, 68)) - d.text((50, y+5), f"{date_str} - Toplam: {total_min} dk", font=header_font, fill=text_color) - y += 50 - - for l in logs_by_date[date_str]: - line = f"• [{l['time']}] {l['task']} ({l['duration']} dk)" - d.text((70, y), line, font=text_font, fill=text_color) - y += 30 - if y > height - 50: break - y += 20 - if y > height - 50: break - - # Kaydetme Yeri (OneDrive Fix) - desktop = get_desktop_path() - filepath = os.path.join(desktop, f"FocusFlow_Rapor_{datetime.date.today()}.png") - img.save(filepath) - - messagebox.showinfo("Başarılı", f"PNG Rapor masaüstüne kaydedildi:\n{filepath}") - - except Exception as e: - messagebox.showerror("Hata", f"Resim oluşturulamadı:\n{e}") - - def export_weekly_report(self): - try: - logs = self.settings.get("session_log", []) - if not logs: messagebox.showinfo("Bilgi", "Henüz kayıt yok."); return - - desktop = get_desktop_path() - filepath = os.path.join(desktop, "FocusFlow_Rapor.txt") - - with open(filepath, "w", encoding="utf-8") as f: - f.write("=== FOCUSFLOW HAFTALIK ÇALIŞMA RAPORU ===\n\n") - today = datetime.date.today() - logs_by_date = {} - for log in logs: - d = log.get("date") - if d not in logs_by_date: logs_by_date[d] = [] - logs_by_date[d].append(log) - - sorted_dates = sorted(logs_by_date.keys(), reverse=True) - for d in sorted_dates: - date_obj = datetime.datetime.strptime(d, "%Y-%m-%d").date() - if (today - date_obj).days > 7: continue - total_min = sum(l['duration'] for l in logs_by_date[d]) - f.write(f"\nTARİH: {d} (Toplam: {total_min} dk)\n") - f.write("-" * 40 + "\n") - for l in logs_by_date[d]: - f.write(f"[{l['time']}] {l['task']} -> {l['duration']} dakika\n") - messagebox.showinfo("Başarılı", f"Rapor masaüstüne kaydedildi:\n{filepath}") - except Exception as e: - messagebox.showerror("Hata", f"Dosya kaydedilemedi:\n{e}") - - def setup_settings(self): - f = self.tab_set - tk.Label(f, text="⚙️ Sistem Ayarları", font=("Segoe UI", 18, "bold"), fg=COLOR_TEXT, bg=COLOR_BG).pack(pady=20) - filter_frame = ttk.LabelFrame(f, text="🛡️ Engelleme Türü") - filter_frame.pack(pady=10, padx=40, fill="x") - self.filter_var = tk.StringVar(value=self.settings.get("filter_mode", "blacklist")) - ttk.Radiobutton(filter_frame, text="⛔ Kara Liste (Engelle)", variable=self.filter_var, value="blacklist", command=lambda: self.settings.update({"filter_mode":"blacklist"})).pack(side="left", padx=20, pady=10) - ttk.Radiobutton(filter_frame, text="✅ Beyaz Liste (Sadece İzin Ver)", variable=self.filter_var, value="whitelist", command=lambda: self.settings.update({"filter_mode":"whitelist"})).pack(side="left", padx=20, pady=10) - - wa_frame = ttk.LabelFrame(f, text="WhatsApp") - wa_frame.pack(pady=10, padx=40, fill="x") - - self.var_wa_enabled = tk.BooleanVar(value=self.settings.get("whatsapp_enabled", True)) - - # --- DÜZELTME BURADA --- - def toggle_wa(): - self.settings["whatsapp_enabled"] = self.var_wa_enabled.get() - self.save_settings() - - tk.Checkbutton(wa_frame, text="Bildirimleri Kullan", variable=self.var_wa_enabled, bg=COLOR_BG, fg=COLOR_TEXT, selectcolor=COLOR_BG, activebackground=COLOR_BG, command=toggle_wa).pack(pady=10, anchor="w", padx=15) - - tk.Label(wa_frame, text="Tel (+90...):", bg=COLOR_BG, fg=COLOR_TEXT).pack(pady=5, anchor="w", padx=15) - self.ent_phone = ttk.Entry(wa_frame); self.ent_phone.insert(0, self.settings["phone"]); self.ent_phone.pack(pady=5, padx=15, anchor="w", fill="x") - - self.create_modern_button(f, "Ayarları Kaydet", lambda:[self.settings.update({"phone":self.ent_phone.get()}), self.save_settings(), messagebox.showinfo("OK","Kaydedildi")], COLOR_SUCCESS, width=20).pack(pady=10) - self.create_modern_button(f, "İstatistik Sıfırla", lambda: [self.settings.update({"stats":{"total_sessions":0,"total_minutes":0,"total_violations":0}, "history":{}, "session_log":[]}), self.save_settings(), self.update_stats_display()], COLOR_DANGER, width=20).pack() - - # --- MANTIK --- - def start_lock(self): - # --- DÜZELTME BURADA: Güvenlik kontrolü --- - wa = self.settings.get("whatsapp_enabled", True) - - # Eğer WA kapalıysa, telefon sormasına gerek yok! - if wa and (not self.settings["phone"] or len(self.settings["phone"])<10): - messagebox.showerror("Hata", "WhatsApp açıkken telefon girmek zorunludur!"); return - - if not self.settings["sites"] and not self.settings["apps"]: messagebox.showwarning("Uyarı", "Liste boş!"); return - task = simpledialog.askstring("Hedef Belirle", "Şu an ne çalışacaksın?\n(Örn: Matematik - Türev)") - if not task: return - self.current_task_name = task - - # WA kapalıysa soru sorma! - if wa and not messagebox.askyesno("WhatsApp", "WhatsApp Web açılsın mı?\n\n⚠️ Mesaj otomatik gidecek, 30 sn DOKUNMA!"): return - - raw_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) - self.lock_hash = hashlib.sha256(raw_code.encode()).hexdigest() - self.is_locked = True - now = datetime.datetime.now() - msg = "" - if self.settings["mode"] == "standard": - try: mins = int(self.spin_std.get()) - except: mins = 60 - self.settings["end_timestamp"] = (now + datetime.timedelta(minutes=mins)).timestamp() - msg = f"🚀 *FocusFlow: {self.current_task_name}*\n\n⏱️ Süre: {mins} dk\n🔐 KOD: {raw_code}" - elif self.settings["mode"] == "pomodoro": - try: - self.settings["pomo_work"] = int(self.spin_p_w.get()); self.settings["pomo_break"] = int(self.spin_p_b.get()) - self.settings["pomo_cycles"] = int(self.spin_cycles.get()) - self.current_cycle_count = 0; self.target_cycles = self.settings["pomo_cycles"] - mins = self.settings["pomo_work"] - self.settings["end_timestamp"] = (now + datetime.timedelta(minutes=mins)).timestamp() - self.pomodoro_state = "WORK" - msg = f"⏱️ *FocusFlow: {self.current_task_name}*\n\n🔄 Hedef: {self.target_cycles} Tur\n📚 Ders: {mins} dk\n🔐 KOD: {raw_code}" - except: return - elif self.settings["mode"] == "flex": - try: - s_h, s_m = map(int, self.ent_flex_start.get().split(':')); e_h, e_m = map(int, self.ent_flex_end.get().split(':')) - start_dt = now.replace(hour=s_h, minute=s_m, second=0) - end_dt = now.replace(hour=e_h, minute=e_m, second=0) - if end_dt < now and end_dt < start_dt: end_dt += datetime.timedelta(days=1) - if start_dt < now: start_dt = now - self.settings["flex_end_timestamp"] = end_dt.timestamp() - self.settings["work_start_timestamp"] = start_dt.timestamp() - self.settings["end_timestamp"] = start_dt.timestamp() - self.settings["flex_break"] = int(self.spin_flex_break.get()) - self.settings["flex_strict"] = self.var_flex_strict.get() - self.pomodoro_state = "WORK" - self.btn_break.pack(pady=10, after=self.btn_start) - msg = f"📅 *FocusFlow: {self.current_task_name}*\n\n⏰ Bitiş: {self.ent_flex_end.get()}\n🔐 KOD: {raw_code}" - except: messagebox.showerror("Hata", "Saat formatı SS:DD olmalı!"); self.is_locked=False; return - self.save_settings(); self.update_ui_state() - - # WA kapalıysa direkt kodu göster - if not wa: messagebox.showinfo("KOD", f"Kod: {raw_code}") - - threading.Thread(target=self.bg_start, args=(self.settings["phone"], msg, wa), daemon=True).start() - - def bg_start(self, phone, msg, wa): - if self.settings.get("filter_mode") != "whitelist" and (self.settings["mode"] != "flex" or datetime.datetime.now().timestamp() >= self.settings["work_start_timestamp"]): - HostsManager.write_blocks(self.settings["sites"]) - if wa: - self.gui_queue.put(("status", "WhatsApp... DOKUNMA!", COLOR_WARNING)) - try: - encoded_msg = urllib.parse.quote(msg) - url = f"https://web.whatsapp.com/send?phone={phone}&text={encoded_msg}" - try: webbrowser.get('brave').open(url) - except: webbrowser.open(url) - time.sleep(30) - pyautogui.press('enter'); time.sleep(1); pyautogui.press('enter') - time.sleep(2); pyautogui.hotkey('ctrl', 'w') - self.gui_queue.put(("wa_success", None)) - except Exception as e: self.gui_queue.put(("wa_error", str(e))) - self.gui_queue.put(("status", "🔒 SİSTEM AKTİF", COLOR_PRIMARY)) - - def record_session(self, duration_mins): - if duration_mins < 1: return - today_str = datetime.date.today().strftime("%Y-%m-%d") - now_time = datetime.datetime.now().strftime("%H:%M") - new_entry = { "date": today_str, "time": now_time, "task": self.current_task_name, "duration": duration_mins } - self.settings["session_log"].append(new_entry) - self.settings["history"][today_str] = self.settings["history"].get(today_str, 0) + duration_mins - self.settings["stats"]["total_sessions"] += 1 - self.settings["stats"]["total_minutes"] += duration_mins - self.save_settings() - - def take_manual_break(self): - now = datetime.datetime.now() - work_duration = int((now.timestamp() - self.settings["work_start_timestamp"]) / 60) - self.pomodoro_state = "BREAK" - break_min = self.settings["flex_break"] - self.settings["end_timestamp"] = (now + datetime.timedelta(minutes=break_min)).timestamp() - self.record_session(work_duration) - HostsManager.clean_hosts() - self.btn_break.config(state="disabled", text=f"☕ Moladasın ({break_min} dk)", bg=COLOR_WARNING) - msg = f"☕ *Mola Zamanı!*\n\n✅ Tamamlanan: {self.current_task_name} ({work_duration} dk)\n🧘 Mola: {break_min} dk" - if self.settings.get("whatsapp_enabled", True) and self.settings["phone"]: - threading.Thread(target=self.send_cycle_message, args=(self.settings["phone"], msg), daemon=True).start() - - def emergency_unlock(self): - c = simpledialog.askstring("ACİL", "Kod:") - if c and hashlib.sha256(c.strip().upper().encode()).hexdigest() == self.lock_hash: - threading.Thread(target=self.bg_unlock, args=("ACİL",), daemon=True).start() - else: messagebox.showerror("HATA", "Yanlış") - - def bg_unlock(self, reason): - HostsManager.clean_hosts() - self.is_locked = False - self.settings["end_timestamp"] = 0 - if reason != "ACİL": - today_str = datetime.date.today().strftime("%Y-%m-%d") - if self.settings.get("last_session_date") != today_str: - self.settings["streak"] = self.settings.get("streak", 0) + 1 - self.settings["last_session_date"] = today_str - self.save_settings() - end_msg = f"🎉 *Oturum Bitti!*\n✅ Durum: {reason}\n⚠️ İhlal: {violation_counter}" - if self.settings.get("whatsapp_enabled", True) and self.settings["phone"]: - threading.Thread(target=self.send_cycle_message, args=(self.settings["phone"], end_msg), daemon=True).start() - self.gui_queue.put(("unlock", reason)) - - def send_cycle_message(self, phone, msg): - try: - encoded_msg = urllib.parse.quote(msg) - url = f"https://web.whatsapp.com/send?phone={phone}&text={encoded_msg}" - try: webbrowser.get('brave').open(url) - except: webbrowser.open(url) - time.sleep(30) - pyautogui.press('enter'); time.sleep(1); pyautogui.press('enter') - time.sleep(2); pyautogui.hotkey('ctrl', 'w') - except: pass - - def handle_pomodoro_cycle(self): - now = datetime.datetime.now(); msg = "" - if self.pomodoro_state == "WORK": - self.pomodoro_state = "BREAK" - mins = self.settings["pomo_break"] - self.settings["end_timestamp"] = (now + datetime.timedelta(minutes=mins)).timestamp() - self.record_session(self.settings["pomo_work"]) - HostsManager.clean_hosts() - msg = f"☕ *Mola Zamanı!*\n\n{mins} dk dinlen. 🧘‍♂️" - self.gui_queue.put(("pomodoro_msg", f"☕ Mola: {mins} dk")) - else: - self.current_cycle_count += 1 - if self.current_cycle_count >= self.target_cycles: - threading.Thread(target=self.bg_unlock, args=("HEDEF TAMAMLANDI",), daemon=True).start(); return - self.pomodoro_state = "WORK" - mins = self.settings["pomo_work"] - self.settings["end_timestamp"] = (now + datetime.timedelta(minutes=mins)).timestamp() - if self.settings.get("filter_mode") != "whitelist": HostsManager.write_blocks(self.settings["sites"]) - msg = f"📚 *Tur {self.current_cycle_count + 1}/{self.target_cycles} Başlıyor!*\n\n{mins} dk odaklan! 🔥" - self.gui_queue.put(("pomodoro_msg", f"📚 Tur {self.current_cycle_count + 1}: {mins} dk")) - if self.settings.get("whatsapp_enabled", True) and self.settings["phone"]: - threading.Thread(target=self.send_cycle_message, args=(self.settings["phone"], msg), daemon=True).start() - - def daemon_loop(self): - while True: - if self.is_locked: - now = datetime.datetime.now(); now_ts = now.timestamp() - - # --- ANTI-CHEAT --- - try: - for proc in psutil.process_iter(['name']): - if proc.info['name'] in ['Taskmgr.exe', 'cmd.exe', 'powershell.exe']: - try: proc.kill() - except: pass - except: pass - - if self.settings["mode"] == "flex": - if now_ts >= self.settings["flex_end_timestamp"]: - threading.Thread(target=self.bg_unlock, args=("GÜN BİTTİ",), daemon=True).start(); time.sleep(5); continue - if self.pomodoro_state == "WORK": - worked_min = int((now_ts - self.settings["work_start_timestamp"]) / 60) - is_strict = self.settings.get("flex_strict", True) - if not is_strict or worked_min >= 40: self.gui_queue.put(("enable_break_btn", True)) - else: self.gui_queue.put(("enable_break_btn", False)) - if self.settings.get("filter_mode") != "whitelist": HostsManager.write_blocks(self.settings["sites"]) - self.gui_queue.put(("status", f"📚 Çalışma: {worked_min} dk", COLOR_DANGER)) - elif self.pomodoro_state == "BREAK": - rem = int(self.settings["end_timestamp"] - now_ts) - if rem <= 0: - self.pomodoro_state = "WORK"; self.settings["work_start_timestamp"] = now_ts - msg = f"📚 *Mola Bitti!*\n\nHadi tekrar derse! Odaklan. 💪" - if self.settings.get("whatsapp_enabled", True): threading.Thread(target=self.send_cycle_message, args=(self.settings["phone"], msg), daemon=True).start() - self.gui_queue.put(("reset_break_btn", None)) - else: - m, s = divmod(rem, 60); self.gui_queue.put(("status", f"☕ Mola Kalan: {m:02d}:{s:02d}", COLOR_SUCCESS)) - else: - if now_ts >= self.settings["end_timestamp"]: - if self.settings["mode"] == "standard": - self.record_session(self.settings["duration"]) - threading.Thread(target=self.bg_unlock, args=("SÜRE DOLDU",), daemon=True).start(); time.sleep(5) - else: self.handle_pomodoro_cycle() - continue - rem = int(self.settings["end_timestamp"] - now_ts); m, s = divmod(rem, 60) - st = f"⏳ Kalan: {m:02d}:{s:02d}" - if self.settings["mode"] == "pomodoro": st = f"{'📚' if self.pomodoro_state=='WORK' else '☕'} {self.pomodoro_state} | Tur: {self.current_cycle_count}/{self.target_cycles} | {st}" - self.gui_queue.put(("status", st, COLOR_DANGER if (self.settings["mode"]=="standard" or self.pomodoro_state=="WORK") else COLOR_SUCCESS)) - - should_block = False - if self.settings["mode"] == "standard": should_block = True - elif self.settings["mode"] == "pomodoro" and self.pomodoro_state == "WORK": should_block = True - elif self.settings["mode"] == "flex" and self.pomodoro_state == "WORK": should_block = True - if should_block: - title, proc_name = get_active_window_info() - browsers = ['brave.exe', 'chrome.exe', 'msedge.exe', 'firefox.exe', 'opera.exe'] - is_whitelist_mode = (self.settings.get("filter_mode") == "whitelist") - found_violation = False - if is_whitelist_mode: - if proc_name in browsers: - is_allowed = False - for site in self.settings["sites"]: - k = site.split('.')[0] - if k in title or (len(k)<2 and (f" {k} " in title)): is_allowed = True - if not is_allowed: found_violation = True - else: - for site in self.settings["sites"]: - # --- YENİ KELİME BAZLI ENGELLEME --- - if "." in site: # Domain ise (youtube.com) - k = site.split('.')[0] - if k in title or (len(k)<2 and (f" {k} " in title)): found_violation = True - else: # Kelime ise (shorts, reels) - if site in title: # Direkt başlıkta ara - found_violation = True - # Eğer kelime yasaklıysa kapat (hosts ile değil, kill ile) - pyautogui.hotkey('ctrl', 'w') - # ----------------------------------- - - if found_violation and proc_name in browsers: - pyautogui.hotkey('ctrl', 'w'); increment_violation(); webbrowser.open(MOTIVATION_URL); time.sleep(1) - - if not is_whitelist_mode: - apps = [a.lower() for a in self.settings["apps"]] - for proc in psutil.process_iter(['name']): - if proc.info['name'].lower() in apps: - try: - proc.kill() - increment_violation() - except: - pass - else: self.gui_queue.put(("status", "✅ Sistem Hazır", COLOR_SUCCESS)) - time.sleep(1) - - def process_gui_queue(self): - try: - while not self.gui_queue.empty(): - i = self.gui_queue.get_nowait() - if i[0] == "status": self.lbl_status.config(text=i[1], fg=i[2]) - elif i[0] == "unlock": self.update_ui_state(); self.graph.draw_graph(); self.update_daily_log_display(); messagebox.showinfo("Bitti", i[1]) - elif i[0] == "wa_success": pass - elif i[0] == "wa_error": messagebox.showwarning("Hata", f"WA Hatası: {i[1]}") - elif i[0] == "pomodoro_msg": pass - elif i[0] == "enable_break_btn": - if i[1]: self.btn_break.config(state="normal", text="☕ MOLA VER (Aktif)", bg=COLOR_PRIMARY) - else: self.btn_break.config(state="disabled", text="☕ MOLA VER (40dk Dolmadı)", bg=COLOR_WARNING) - elif i[0] == "reset_break_btn": - self.btn_break.config(state="disabled", text="☕ MOLA VER (40dk Dolmadı)", bg=COLOR_WARNING) - except: pass - self.root.after(200, self.process_gui_queue) - - def update_stats_display(self): - try: - self.update_daily_log_display() - self.graph.draw_graph() - except: pass - self.root.after(10000, self.update_stats_display) - - def update_ui_state(self): - st = "disabled" if self.is_locked else "normal" - self.btn_start.config(state=st) - self.btn_emerg.config(state="normal" if self.is_locked else "disabled") - if not self.is_locked: self.btn_break.pack_forget() - for i in [1,2,3,5]: - try: self.notebook.tab(i, state=st) - except: pass - - def on_close(self): - if self.is_locked: messagebox.showwarning("Dur", "Çalışma bitmeden kapatılamaz!"); self.root.iconify() - elif messagebox.askyesno("Çıkış", "Kapatılsın mı?"): HostsManager.clean_hosts(); self.root.destroy(); sys.exit() - -if __name__ == "__main__": - # --- YÖNETİCİ İZNİ KONTROLÜ VE OTO-YÜKSELTME --- - def is_admin(): - try: - return ctypes.windll.shell32.IsUserAnAdmin() - except: - return False - - if not is_admin(): - ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) - sys.exit() - else: - root = tk.Tk() - app = FocusFlow(root) - root.mainloop() diff --git a/pkg/engine/anticheat.go b/pkg/engine/anticheat.go index 2253b39..a5f812a 100644 --- a/pkg/engine/anticheat.go +++ b/pkg/engine/anticheat.go @@ -8,6 +8,16 @@ const ( StrictnessHardcore StrictnessLevel = "hardcore" ) +var HardcoreAntiCheatBinaries = []string{ + "taskmgr.exe", + "processhacker.exe", + "SystemInformer.exe", + "procmon.exe", + "procmon64.exe", + "procexp.exe", + "procexp64.exe", +} + type AntiCheatGuard struct { level StrictnessLevel supervisor *ProcessSupervisor @@ -16,12 +26,7 @@ type AntiCheatGuard struct { func NewAntiCheatGuard(level StrictnessLevel) *AntiCheatGuard { var blocked []string if level == StrictnessHardcore { - blocked = []string{ - "taskmgr.exe", - "processhacker.exe", - "procmon.exe", - "procexp.exe", - } + blocked = append(blocked, HardcoreAntiCheatBinaries...) } return &AntiCheatGuard{ level: level, diff --git a/pkg/engine/dns.go b/pkg/engine/dns.go index bfac55b..b7e662e 100644 --- a/pkg/engine/dns.go +++ b/pkg/engine/dns.go @@ -5,6 +5,22 @@ import ( "runtime" ) +var defaultDoHBypassDomains = []string{ + "cloudflare-dns.com", + "one.one.one.one", + "chrome.cloudflare-dns.com", + "mozilla.cloudflare-dns.com", + "dns.google", + "dns.google.com", + "dns.quad9.net", + "doh.opendns.com", + "dns.adguard-dns.com", + "dns.nextdns.io", + "doh.cleanbrowsing.org", + "doh.dns.sb", + "freedns.controld.com", +} + type DnsEngine struct{} func (d *DnsEngine) FlushResolverCache() error { @@ -14,7 +30,11 @@ func (d *DnsEngine) FlushResolverCache() error { return cmd.Run() case "darwin": cmd := exec.Command("dscacheutil", "-flushcache") - return cmd.Run() + if err := cmd.Run(); err != nil { + return err + } + _ = exec.Command("killall", "-HUP", "mDNSResponder").Run() + return nil default: cmd := exec.Command("resolvectl", "flush-caches") if err := cmd.Run(); err != nil { @@ -24,15 +44,14 @@ func (d *DnsEngine) FlushResolverCache() error { } } +func (d *DnsEngine) FlushResolverCacheAsync() { + go func() { + _ = d.FlushResolverCache() + }() +} + func (d *DnsEngine) GetDoHBypassDomains() []string { - return []string{ - "cloudflare-dns.com", - "one.one.one.one", - "dns.google", - "dns.google.com", - "dns.quad9.net", - "doh.opendns.com", - "chrome.cloudflare-dns.com", - "mozilla.cloudflare-dns.com", - } + out := make([]string, len(defaultDoHBypassDomains)) + copy(out, defaultDoHBypassDomains) + return out } diff --git a/pkg/engine/fileio_posix.go b/pkg/engine/fileio_posix.go new file mode 100644 index 0000000..caeaf73 --- /dev/null +++ b/pkg/engine/fileio_posix.go @@ -0,0 +1,113 @@ +//go:build !windows + +package engine + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "syscall" + "time" +) + +const ( + maxPosixWriteRetries = 5 + posixWriteRetryBackoff = 40 * time.Millisecond +) + +// writeHostsFileSafe atomically updates hostsPath while preserving existing POSIX permissions +// (defaulting to 0644 rather than CreateTemp's 0600 so non-root DNS resolution never breaks). +func writeHostsFileSafe(hostsPath string, content []byte) error { + dir := filepath.Dir(hostsPath) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + targetMode := os.FileMode(0644) + if info, err := os.Stat(hostsPath); err == nil { + targetMode = info.Mode().Perm() + if targetMode == 0 { + targetMode = 0644 + } + } + + var lastErr error + for attempt := 0; attempt < maxPosixWriteRetries; attempt++ { + tmpFile, err := os.CreateTemp(dir, "focusflow-hosts-*.tmp") + if err != nil { + lastErr = err + if attempt+1 < maxPosixWriteRetries { + time.Sleep(posixWriteRetryBackoff) + continue + } + return lastErr + } + tmpPath := tmpFile.Name() + + if err := tmpFile.Chmod(targetMode); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if _, err := tmpFile.Write(content); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Sync(); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := os.Rename(tmpPath, hostsPath); err == nil { + return nil + } else { + lastErr = err + _ = os.Remove(tmpPath) + if attempt+1 < maxPosixWriteRetries { + time.Sleep(posixWriteRetryBackoff) + } + } + } + return lastErr +} + +func readHostsFileWithRetry(hostsPath string) ([]byte, error) { + return os.ReadFile(hostsPath) +} + +// IsElevated reports whether the current POSIX process runs as root (euid == 0). +func IsElevated() bool { + return os.Geteuid() == 0 +} + +// ElevateSelf re-invokes the current binary via sudo on POSIX platforms. +func ElevateSelf(args []string) error { + exePath, err := os.Executable() + if err != nil { + return err + } + sudoArgs := append([]string{exePath}, args...) + cmd := exec.Command("sudo", sudoArgs...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} + +// IsPIDAlive checks whether a process with the given PID exists on POSIX platforms. +func IsPIDAlive(pid int) bool { + if pid <= 0 { + return false + } + if pid == os.Getpid() { + return true + } + err := syscall.Kill(pid, 0) + return err == nil || errors.Is(err, syscall.EPERM) +} diff --git a/pkg/engine/fileio_windows.go b/pkg/engine/fileio_windows.go new file mode 100644 index 0000000..3244975 --- /dev/null +++ b/pkg/engine/fileio_windows.go @@ -0,0 +1,248 @@ +//go:build windows + +package engine + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + replaceFileIgnoreMergeErrors = 0x00000002 + processQueryLimitedInformation = 0x00001000 + win32StillActive = 259 + win32ErrorSharingViolation = syscall.Errno(32) + win32ErrorLockViolation = syscall.Errno(33) + maxWindowsWriteRetries = 5 + windowsWriteRetryBackoff = 40 * time.Millisecond +) + +var ( + modKernel32 = syscall.NewLazyDLL("kernel32.dll") + modShell32 = syscall.NewLazyDLL("shell32.dll") + procReplaceFileW = modKernel32.NewProc("ReplaceFileW") + procIsUserAnAdmin = modShell32.NewProc("IsUserAnAdmin") + procShellExecuteW = modShell32.NewProc("ShellExecuteW") +) + +func isTransientSharingError(err error) bool { + if err == nil { + return false + } + var errno syscall.Errno + if errors.As(err, &errno) { + return errno == win32ErrorSharingViolation || errno == win32ErrorLockViolation + } + return false +} + +// writeHostsFileSafe writes content to hostsPath while preserving existing Windows DACLs +// (ensuring NetworkService / Dnscache and Users retain read access), syncing to disk, +// and retrying transient sharing locks (5x with 40ms backoff). +func writeHostsFileSafe(hostsPath string, content []byte) error { + dir := filepath.Dir(hostsPath) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + tmpFile, err := os.CreateTemp(dir, "focusflow-hosts-*.tmp") + if err != nil { + return err + } + tmpPath := tmpFile.Name() + + if _, err := tmpFile.Write(content); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Sync(); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + + // If target file does not exist yet, atomic rename with inherited parent permissions + if _, statErr := os.Stat(hostsPath); os.IsNotExist(statErr) { + var lastErr error + for attempt := 0; attempt < maxWindowsWriteRetries; attempt++ { + if err := os.Rename(tmpPath, hostsPath); err == nil { + return nil + } else { + lastErr = err + if attempt+1 < maxWindowsWriteRetries { + time.Sleep(windowsWriteRetryBackoff) + } + } + } + _ = os.Remove(tmpPath) + return lastErr + } + + // Target exists: use Win32 ReplaceFileW to atomically swap data while preserving target DACLs + targetPtr, err := syscall.UTF16PtrFromString(hostsPath) + if err != nil { + _ = os.Remove(tmpPath) + return err + } + tempPtr, err := syscall.UTF16PtrFromString(tmpPath) + if err != nil { + _ = os.Remove(tmpPath) + return err + } + + var lastReplaceErr error + for attempt := 0; attempt < maxWindowsWriteRetries; attempt++ { + r1, _, callErr := procReplaceFileW.Call( + uintptr(unsafe.Pointer(targetPtr)), + uintptr(unsafe.Pointer(tempPtr)), + 0, + uintptr(replaceFileIgnoreMergeErrors), + 0, + 0, + ) + if r1 != 0 { + return nil + } + lastReplaceErr = callErr + if attempt+1 < maxWindowsWriteRetries { + time.Sleep(windowsWriteRetryBackoff) + } + } + + // Clean up temp file before in-place DACL-preserving fallback + _ = os.Remove(tmpPath) + + var lastFallbackErr error + for attempt := 0; attempt < maxWindowsWriteRetries; attempt++ { + f, openErr := os.OpenFile(hostsPath, os.O_WRONLY|os.O_TRUNC, 0644) + if openErr != nil { + lastFallbackErr = openErr + if isTransientSharingError(openErr) && attempt+1 < maxWindowsWriteRetries { + time.Sleep(windowsWriteRetryBackoff) + continue + } + break + } + _, writeErr := f.Write(content) + syncErr := f.Sync() + closeErr := f.Close() + if writeErr == nil && syncErr == nil && closeErr == nil { + return nil + } + if writeErr != nil { + lastFallbackErr = writeErr + } else if syncErr != nil { + lastFallbackErr = syncErr + } else { + lastFallbackErr = closeErr + } + if attempt+1 < maxWindowsWriteRetries { + time.Sleep(windowsWriteRetryBackoff) + } + } + + if lastFallbackErr != nil { + return lastFallbackErr + } + return lastReplaceErr +} + +func readHostsFileWithRetry(hostsPath string) ([]byte, error) { + var lastErr error + for attempt := 0; attempt < maxWindowsWriteRetries; attempt++ { + data, err := os.ReadFile(hostsPath) + if err == nil { + return data, nil + } + lastErr = err + if isTransientSharingError(err) && attempt+1 < maxWindowsWriteRetries { + time.Sleep(windowsWriteRetryBackoff) + continue + } + break + } + return nil, lastErr +} + +// IsElevated reports whether the current Windows process holds Administrator privileges. +func IsElevated() bool { + r1, _, _ := procIsUserAnAdmin.Call() + return r1 != 0 +} + +// ElevateSelf re-launches the current FocusFlow binary under UAC "runas" elevation, +// safely quoting paths and arguments containing spaces. +func ElevateSelf(args []string) error { + exePath, err := os.Executable() + if err != nil { + return err + } + quoted := make([]string, 0, len(args)) + for _, a := range args { + quoted = append(quoted, syscall.EscapeArg(a)) + } + paramStr := strings.Join(quoted, " ") + cwd, _ := os.Getwd() + + verbPtr, err := syscall.UTF16PtrFromString("runas") + if err != nil { + return err + } + exePtr, err := syscall.UTF16PtrFromString(exePath) + if err != nil { + return err + } + paramPtr, err := syscall.UTF16PtrFromString(paramStr) + if err != nil { + return err + } + cwdPtr, err := syscall.UTF16PtrFromString(cwd) + if err != nil { + return err + } + + r1, _, callErr := procShellExecuteW.Call( + 0, + uintptr(unsafe.Pointer(verbPtr)), + uintptr(unsafe.Pointer(exePtr)), + uintptr(unsafe.Pointer(paramPtr)), + uintptr(unsafe.Pointer(cwdPtr)), + 1, // SW_SHOWNORMAL + ) + if r1 <= 32 { + return fmt.Errorf("UAC elevation cancelled or failed (code %d: %v)", r1, callErr) + } + return nil +} + +// IsPIDAlive checks whether a process with the given PID is currently active on Windows. +func IsPIDAlive(pid int) bool { + if pid <= 0 { + return false + } + if pid == os.Getpid() { + return true + } + h, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid)) + if err != nil { + return errors.Is(err, syscall.ERROR_ACCESS_DENIED) + } + defer syscall.CloseHandle(h) + + var exitCode uint32 + if err := syscall.GetExitCodeProcess(h, &exitCode); err != nil { + return false + } + return exitCode == win32StillActive +} diff --git a/pkg/engine/hosts.go b/pkg/engine/hosts.go index e43cf89..af0f9ad 100644 --- a/pkg/engine/hosts.go +++ b/pkg/engine/hosts.go @@ -3,43 +3,117 @@ package engine import ( "crypto/sha256" "encoding/hex" + "encoding/json" "fmt" "io" "os" "path/filepath" "runtime" "strings" + "time" + + "github.com/aloneangel45/focusflow/pkg/storage" ) const ( - DefaultHostsPath = `C:\Windows\System32\drivers\etc\hosts` - MarkerBegin = "# --- BEGIN FOCUSFLOW MANAGED BLOCK ---" - MarkerEnd = "# --- END FOCUSFLOW MANAGED BLOCK ---" + DefaultWindowsHostsPath = `C:\Windows\System32\drivers\etc\hosts` + DefaultPosixHostsPath = "/etc/hosts" + DefaultHostsPath = DefaultWindowsHostsPath + + MarkerBegin = "# --- BEGIN FOCUSFLOW MANAGED BLOCK ---" + MarkerEnd = "# --- END FOCUSFLOW MANAGED BLOCK ---" + LegacyMarkerBegin = "# --- FOCUSFLOW BLOCK START ---" + LegacyMarkerEnd = "# --- FOCUSFLOW BLOCK END ---" + + BackupFilename = "hosts.focusflow.bak" + JournalFilename = "hosts.focusflow.journal.json" ) +type HostsJournal struct { + OriginalSHA256 string `json:"original_sha256"` + BackupPath string `json:"backup_path"` + HostsPath string `json:"hosts_path"` + SessionID string `json:"session_id"` + PID int `json:"pid"` + StartedAt string `json:"started_at"` + ExpectedEndAt string `json:"expected_end_at"` + Profile string `json:"profile"` +} + +type SessionMeta struct { + SessionID string + PID int + StartedAt time.Time + ExpectedEndAt time.Time + Profile string +} + +type RecoveryResult struct { + Recovered bool `json:"recovered"` + UsedFallback bool `json:"used_fallback"` + OrphanSessionID string `json:"orphan_session_id,omitempty"` + ActiveOwnerPID int `json:"active_owner_pid,omitempty"` + RestoredChecksum string `json:"restored_checksum,omitempty"` + Reason string `json:"reason,omitempty"` +} + type HostsManager struct { - hostsPath string - backupPath string + hostsPath string + stateDir string + backupPath string + journalPath string } -func GetDefaultHostsPath() string { +func systemDefaultHostsPath() string { if runtime.GOOS == "windows" { - return DefaultHostsPath + return DefaultWindowsHostsPath } - return "/etc/hosts" + return DefaultPosixHostsPath +} + +func GetDefaultHostsPath() string { + if override := strings.TrimSpace(os.Getenv("FOCUSFLOW_HOSTS_PATH")); override != "" { + return filepath.Clean(override) + } + return systemDefaultHostsPath() } func NewHostsManager() *HostsManager { - return NewHostsManagerWithPath(GetDefaultHostsPath()) + return NewHostsManagerWithState(GetDefaultHostsPath(), storage.GetStateDir()) } func NewHostsManagerWithPath(path string) *HostsManager { + cleanPath := filepath.Clean(path) + var stateDir string + if strings.TrimSpace(os.Getenv("FOCUSFLOW_HOME")) != "" { + stateDir = storage.GetStateDir() + } else if cleanPath != filepath.Clean(systemDefaultHostsPath()) { + // Hermetic test isolation: never write to real %APPDATA% when a custom hosts path is supplied + stateDir = filepath.Dir(cleanPath) + } else { + stateDir = storage.GetStateDir() + } + return NewHostsManagerWithState(cleanPath, stateDir) +} + +func NewHostsManagerWithState(hostsPath, stateDir string) *HostsManager { return &HostsManager{ - hostsPath: path, - backupPath: path + ".focusflow.bak", + hostsPath: hostsPath, + stateDir: stateDir, + backupPath: filepath.Join(stateDir, BackupFilename), + journalPath: filepath.Join(stateDir, JournalFilename), } } +func (h *HostsManager) HostsPath() string { return h.hostsPath } +func (h *HostsManager) BackupPath() string { return h.backupPath } +func (h *HostsManager) JournalPath() string { return h.journalPath } + +func ComputeBytesSHA256(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + func (h *HostsManager) ComputeSHA256(path string) (string, error) { f, err := os.Open(path) if err != nil { @@ -54,132 +128,531 @@ func (h *HostsManager) ComputeSHA256(path string) (string, error) { return hex.EncodeToString(hasher.Sum(nil)), nil } +func HasManagedMarkers(content string) bool { + return strings.Contains(content, MarkerBegin) || + strings.Contains(content, MarkerEnd) || + strings.Contains(content, LegacyMarkerBegin) || + strings.Contains(content, LegacyMarkerEnd) +} + +func detectLineEnding(content string) string { + if strings.Contains(content, "\r\n") { + return "\r\n" + } + if strings.Contains(content, "\n") { + return "\n" + } + if runtime.GOOS == "windows" { + return "\r\n" + } + return "\n" +} + +func isBeginMarkerLine(trimmed string) bool { + t := strings.TrimSpace(trimmed) + return t == MarkerBegin || t == LegacyMarkerBegin || + strings.Contains(trimmed, MarkerBegin) || strings.Contains(trimmed, LegacyMarkerBegin) +} + +func isEndMarkerLine(trimmed string) bool { + t := strings.TrimSpace(trimmed) + return t == MarkerEnd || t == LegacyMarkerEnd || + strings.Contains(trimmed, MarkerEnd) || strings.Contains(trimmed, LegacyMarkerEnd) +} + +func isLikelyFocusFlowSinkholeLine(trimmed string) bool { + t := strings.TrimSpace(trimmed) + if t == "" { + return true + } + if strings.HasPrefix(t, "#") { + lower := strings.ToLower(t) + return strings.Contains(lower, "focusflow") || strings.Contains(lower, "managed") || strings.Contains(lower, "sinkhole") || strings.Contains(lower, "distraction") + } + fields := strings.Fields(t) + if len(fields) < 2 { + return false + } + ip := fields[0] + host := strings.ToLower(fields[1]) + if ip == "0.0.0.0" || ip == "::" { + return true + } + if ip == "127.0.0.1" && host != "localhost" && host != "localhost.localdomain" { + return true + } + return false +} + +// StripManagedBlocks removes all current and legacy FocusFlow managed blocks deterministically. +// Safely handles missing/truncated end markers without string-slice corruption, and preserves +// original bytes unchanged when no FocusFlow markers exist. +func StripManagedBlocks(content string) string { + if !HasManagedMarkers(content) { + return content + } + + eol := detectLineEnding(content) + hadTrailingNewline := strings.HasSuffix(content, "\n") + + rawLines := strings.Split(content, "\n") + if hadTrailingNewline && len(rawLines) > 0 && rawLines[len(rawLines)-1] == "" { + rawLines = rawLines[:len(rawLines)-1] + } + + lines := make([]string, len(rawLines)) + for i, l := range rawLines { + lines[i] = strings.TrimSuffix(l, "\r") + } + + kept := make([]string, 0, len(lines)) + i := 0 + for i < len(lines) { + line := lines[i] + if isBeginMarkerLine(line) { + // Pop at most one separator blank line added before MarkerBegin + if len(kept) > 0 && strings.TrimSpace(kept[len(kept)-1]) == "" { + kept = kept[:len(kept)-1] + } + + // Look ahead to see if a matching end marker exists before another begin marker or EOF + endIdx := -1 + for j := i + 1; j < len(lines); j++ { + if isEndMarkerLine(lines[j]) { + endIdx = j + break + } + if isBeginMarkerLine(lines[j]) { + break + } + } + + if endIdx >= 0 { + i = endIdx + 1 + continue + } + + // Missing end marker: consume FocusFlow comments/sinkhole lines safely without eating custom user entries + i++ + for i < len(lines) { + if isBeginMarkerLine(lines[i]) { + break + } + if isEndMarkerLine(lines[i]) { + i++ + break + } + if isLikelyFocusFlowSinkholeLine(lines[i]) { + i++ + continue + } + break + } + continue + } + + if isEndMarkerLine(line) { + // Stray orphan end marker + i++ + continue + } + + kept = append(kept, line) + i++ + } + + if len(kept) == 0 { + return "" + } + out := strings.Join(kept, eol) + if hadTrailingNewline { + out += eol + } + return out +} + +func (h *HostsManager) stripManagedBlock(content string) string { + return StripManagedBlocks(content) +} + +func writeAtomicStateFile(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + tmpFile, err := os.CreateTemp(dir, "ff-state-*.tmp") + if err != nil { + return err + } + tmpPath := tmpFile.Name() + if _, err := tmpFile.Write(data); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Sync(); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + if err := tmpFile.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Chmod(tmpPath, 0644) + if err := os.Rename(tmpPath, path); err != nil { + if wErr := os.WriteFile(path, data, 0644); wErr != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Remove(tmpPath) + } + return nil +} + +// Backup creates a guaranteed-clean baseline backup of the hosts file (stripping any +// existing FocusFlow markers first so a contaminated hosts file is NEVER backed up) +// and returns the clean baseline SHA-256 hex digest. func (h *HostsManager) Backup() (string, error) { if _, err := os.Stat(h.hostsPath); os.IsNotExist(err) { return "", fmt.Errorf("hosts file not found at %s", h.hostsPath) } - data, err := os.ReadFile(h.hostsPath) + rawData, err := readHostsFileWithRetry(h.hostsPath) if err != nil { return "", err } - if err := os.WriteFile(h.backupPath, data, 0644); err != nil { + cleanContent := StripManagedBlocks(string(rawData)) + cleanBytes := []byte(cleanContent) + + if err := writeAtomicStateFile(h.backupPath, cleanBytes); err != nil { return "", err } - return h.ComputeSHA256(h.backupPath) + return ComputeBytesSHA256(cleanBytes), nil +} + +func (h *HostsManager) LoadJournal() (*HostsJournal, error) { + raw, err := os.ReadFile(h.journalPath) + if err != nil { + return nil, err + } + var j HostsJournal + if err := json.Unmarshal(raw, &j); err != nil { + return nil, err + } + return &j, nil +} + +func (h *HostsManager) writeJournal(j *HostsJournal) error { + payload, err := json.MarshalIndent(j, "", " ") + if err != nil { + return err + } + payload = append(payload, '\n') + return writeAtomicStateFile(h.journalPath, payload) +} + +func BuildManagedBlock(sanitizedDomains []string, eol string) string { + var b strings.Builder + b.WriteString(MarkerBegin) + b.WriteString(eol) + b.WriteString("# FocusFlow v2.1 - Dual-Stack Managed Sinkhole") + b.WriteString(eol) + for _, d := range sanitizedDomains { + b.WriteString("0.0.0.0 ") + b.WriteString(d) + b.WriteString(eol) + if !strings.HasPrefix(d, "www.") { + b.WriteString("0.0.0.0 www.") + b.WriteString(d) + b.WriteString(eol) + } + b.WriteString(":: ") + b.WriteString(d) + b.WriteString(eol) + if !strings.HasPrefix(d, "www.") { + b.WriteString(":: www.") + b.WriteString(d) + b.WriteString(eol) + } + } + b.WriteString(MarkerEnd) + b.WriteString(eol) + return b.String() } func (h *HostsManager) ApplyBlocklist(domains []string) error { - if len(domains) == 0 { + now := time.Now().UTC() + return h.ApplyBlocklistWithSession(domains, SessionMeta{ + SessionID: storage.GenerateSessionID(), + PID: os.Getpid(), + StartedAt: now, + ExpectedEndAt: now.Add(2 * time.Hour), + Profile: "default", + }) +} + +func (h *HostsManager) ApplyBlocklistWithSession(domains []string, meta SessionMeta) error { + cleanDomains := SanitizeDomains(domains) + if len(cleanDomains) == 0 { return nil } - // Ensure backup exists - if _, err := os.Stat(h.backupPath); os.IsNotExist(err) { - if _, err := h.Backup(); err != nil { - return fmt.Errorf("failed to create hosts backup: %w", err) - } + if _, err := os.Stat(h.hostsPath); os.IsNotExist(err) { + return fmt.Errorf("hosts file not found at %s", h.hostsPath) } - data, err := os.ReadFile(h.hostsPath) + rawData, err := readHostsFileWithRetry(h.hostsPath) if err != nil { return err } - cleanContent := h.stripManagedBlock(string(data)) + cleanBaseline := StripManagedBlocks(string(rawData)) + cleanBytes := []byte(cleanBaseline) + baselineSHA := ComputeBytesSHA256(cleanBytes) - var b strings.Builder - b.WriteString("\n") - b.WriteString(MarkerBegin) - b.WriteString("\n# FocusFlow V2 - Distraction-free system guard\n") - - for _, d := range domains { - d = strings.ToLower(strings.TrimSpace(d)) - if d != "" && !strings.HasPrefix(d, "#") { - b.WriteString(fmt.Sprintf("0.0.0.0 %s\n", d)) - if !strings.HasPrefix(d, "www.") { - b.WriteString(fmt.Sprintf("0.0.0.0 www.%s\n", d)) + // Reuse existing verified clean backup if present; otherwise create a fresh clean backup + needFreshBackup := true + if existingJournal, jErr := h.LoadJournal(); jErr == nil && existingJournal.OriginalSHA256 != "" { + if bakData, bErr := os.ReadFile(h.backupPath); bErr == nil { + if !HasManagedMarkers(string(bakData)) && ComputeBytesSHA256(bakData) == existingJournal.OriginalSHA256 { + baselineSHA = existingJournal.OriginalSHA256 + needFreshBackup = false } } } - b.WriteString(MarkerEnd) - b.WriteString("\n") + if needFreshBackup { + if err := writeAtomicStateFile(h.backupPath, cleanBytes); err != nil { + return fmt.Errorf("failed to create clean hosts backup: %w", err) + } + } - newContent := strings.TrimRight(cleanContent, "\r\n") + b.String() + now := time.Now().UTC() + if meta.PID <= 0 { + meta.PID = os.Getpid() + } + if meta.SessionID == "" { + meta.SessionID = storage.GenerateSessionID() + } + if meta.StartedAt.IsZero() { + meta.StartedAt = now + } + if meta.ExpectedEndAt.IsZero() { + meta.ExpectedEndAt = meta.StartedAt.Add(60 * time.Minute) + } + if meta.Profile == "" { + meta.Profile = "study" + } - // Atomic write via temp file in same directory - dir := filepath.Dir(h.hostsPath) - tmpFile, err := os.CreateTemp(dir, "focusflow-hosts-*.tmp") - if err != nil { - return err + journal := &HostsJournal{ + OriginalSHA256: baselineSHA, + BackupPath: h.backupPath, + HostsPath: h.hostsPath, + SessionID: meta.SessionID, + PID: meta.PID, + StartedAt: meta.StartedAt.UTC().Format(time.RFC3339), + ExpectedEndAt: meta.ExpectedEndAt.UTC().Format(time.RFC3339), + Profile: meta.Profile, } - tmpPath := tmpFile.Name() - if _, err := tmpFile.WriteString(newContent); err != nil { - tmpFile.Close() - os.Remove(tmpPath) - return err + // Write-Ahead Rollback Journal persisted and synced BEFORE hosts modification + if err := h.writeJournal(journal); err != nil { + return fmt.Errorf("failed to persist write-ahead hosts journal: %w", err) } - tmpFile.Close() - return os.Rename(tmpPath, h.hostsPath) + eol := detectLineEnding(cleanBaseline) + block := BuildManagedBlock(cleanDomains, eol) + + trimmedBase := strings.TrimRight(cleanBaseline, "\r\n") + var newContent string + if trimmedBase == "" { + newContent = block + } else { + newContent = trimmedBase + eol + eol + block + } + + return writeHostsFileSafe(h.hostsPath, []byte(newContent)) } +// VerifyOrReapply checks mid-session integrity of the managed block in hosts and re-applies +// the sinkhole if any tampering or external overwrite occurred. +func (h *HostsManager) VerifyOrReapply(domains []string, meta SessionMeta) (bool, error) { + cleanDomains := SanitizeDomains(domains) + if len(cleanDomains) == 0 { + return false, nil + } + + rawData, err := readHostsFileWithRetry(h.hostsPath) + if err != nil { + return false, err + } + content := string(rawData) + if !strings.Contains(content, MarkerBegin) || !strings.Contains(content, MarkerEnd) { + return true, h.ApplyBlocklistWithSession(cleanDomains, meta) + } + + for _, d := range cleanDomains { + v4 := "0.0.0.0 " + d + v6 := ":: " + d + if !strings.Contains(content, v4) || !strings.Contains(content, v6) { + return true, h.ApplyBlocklistWithSession(cleanDomains, meta) + } + } + return false, nil +} + +// Rollback restores the clean hosts file using SHA-256 verified backup or deterministic +// marker stripping fallback, then cleans up journal and backup artifacts. func (h *HostsManager) Rollback() error { - if _, err := os.Stat(h.backupPath); err == nil { - data, err := os.ReadFile(h.backupPath) - if err == nil { - if err := os.WriteFile(h.hostsPath, data, 0644); err == nil { - _ = os.Remove(h.backupPath) - return nil + _, err := h.restoreHostsFromBackupOrStrip() + if err != nil { + return err + } + h.cleanupStateArtifacts() + return nil +} + +func (h *HostsManager) restoreHostsFromBackupOrStrip() (usedFallback bool, err error) { + journal, jErr := h.LoadJournal() + backupPath := h.backupPath + if jErr == nil && journal.BackupPath != "" { + backupPath = journal.BackupPath + } + + if bakData, bErr := os.ReadFile(backupPath); bErr == nil { + bakClean := !HasManagedMarkers(string(bakData)) + hashMatches := true + if jErr == nil && journal.OriginalSHA256 != "" { + hashMatches = ComputeBytesSHA256(bakData) == journal.OriginalSHA256 + } + if bakClean && hashMatches { + if wErr := writeHostsFileSafe(h.hostsPath, bakData); wErr == nil { + return false, nil } } } - // Fallback: strip managed block directly - if _, err := os.Stat(h.hostsPath); err == nil { - data, err := os.ReadFile(h.hostsPath) - if err != nil { - return err + // Fallback: deterministic marker stripping directly on hostsPath + if _, statErr := os.Stat(h.hostsPath); statErr == nil { + rawData, rErr := readHostsFileWithRetry(h.hostsPath) + if rErr != nil { + return true, rErr + } + clean := StripManagedBlocks(string(rawData)) + if wErr := writeHostsFileSafe(h.hostsPath, []byte(clean)); wErr != nil { + return true, wErr } - clean := h.stripManagedBlock(string(data)) - return os.WriteFile(h.hostsPath, []byte(clean), 0644) + return true, nil } - return nil + return false, nil } -func (h *HostsManager) stripManagedBlock(content string) string { - var result strings.Builder - insideBlock := false - - lines := strings.Split(content, "\n") - for _, line := range lines { - trimmed := strings.TrimRight(line, "\r") - if strings.Contains(trimmed, MarkerBegin) { - insideBlock = true - continue - } - if strings.Contains(trimmed, MarkerEnd) { - insideBlock = false - continue +func (h *HostsManager) cleanupStateArtifacts() { + _ = os.Remove(h.journalPath) + _ = os.Remove(h.backupPath) + // Also clean up any legacy adjacent backup file from v2.0 + _ = os.Remove(h.hostsPath + ".focusflow.bak") +} + +func isJournalExpired(expectedEndAt string, now time.Time) bool { + expectedEndAt = strings.TrimSpace(expectedEndAt) + if expectedEndAt == "" { + return false + } + t, err := time.Parse(time.RFC3339, expectedEndAt) + if err != nil { + return false + } + return now.After(t) +} + +// RecoverIfOrphaned inspects the write-ahead journal and hosts file on startup. +// If an orphaned crash/reboot state or expired lock is found, it verifies .bak SHA-256 +// (falling back to deterministic marker stripping if altered/missing), restores hosts, +// flushes DNS asynchronously, and invokes onOrphanSession so sessions.json marks completed: false. +func (h *HostsManager) RecoverIfOrphaned(onOrphanSession func(sessionID string)) (*RecoveryResult, error) { + return h.RecoverIfOrphanedAt(time.Now().UTC(), onOrphanSession) +} + +func (h *HostsManager) RecoverIfOrphanedAt(now time.Time, onOrphanSession func(sessionID string)) (*RecoveryResult, error) { + journal, jErr := h.LoadJournal() + hasJournal := jErr == nil && journal != nil + hasCorruptJournal := false + if jErr != nil && !os.IsNotExist(jErr) { + hasCorruptJournal = true + } + + hostsHasMarkers := false + if rawData, err := readHostsFileWithRetry(h.hostsPath); err == nil { + hostsHasMarkers = HasManagedMarkers(string(rawData)) + } + + if !hasJournal && !hasCorruptJournal && !hostsHasMarkers { + return &RecoveryResult{Recovered: false, Reason: "clean"}, nil + } + + reason := "stray_markers_without_journal" + orphanSessionID := "" + + if hasJournal { + orphanSessionID = journal.SessionID + expired := isJournalExpired(journal.ExpectedEndAt, now) + pidAlive := journal.PID > 0 && IsPIDAlive(journal.PID) + + if pidAlive && !expired { + return &RecoveryResult{ + Recovered: false, + ActiveOwnerPID: journal.PID, + Reason: "active_session_alive", + }, nil } - if !insideBlock { - result.WriteString(trimmed) - result.WriteString("\n") + if !pidAlive { + reason = fmt.Sprintf("owner_pid_%d_dead", journal.PID) + } else { + reason = "session_lease_expired" } + } else if hasCorruptJournal { + reason = "corrupt_journal" } - return result.String() + usedFallback, err := h.restoreHostsFromBackupOrStrip() + if err != nil { + return &RecoveryResult{ + Recovered: false, + UsedFallback: usedFallback, + OrphanSessionID: orphanSessionID, + Reason: reason, + }, err + } + + h.cleanupStateArtifacts() + + if onOrphanSession != nil { + onOrphanSession(orphanSessionID) + } + + dns := &DnsEngine{} + dns.FlushResolverCacheAsync() + + restoredSum, _ := h.ComputeSHA256(h.hostsPath) + return &RecoveryResult{ + Recovered: true, + UsedFallback: usedFallback, + OrphanSessionID: orphanSessionID, + RestoredChecksum: restoredSum, + Reason: reason, + }, nil } func (h *HostsManager) IsActive() bool { - data, err := os.ReadFile(h.hostsPath) + data, err := readHostsFileWithRetry(h.hostsPath) if err != nil { return false } - return strings.Contains(string(data), MarkerBegin) + s := string(data) + return strings.Contains(s, MarkerBegin) || strings.Contains(s, LegacyMarkerBegin) } diff --git a/pkg/engine/hosts_test.go b/pkg/engine/hosts_test.go index 62f9bd9..7caca41 100644 --- a/pkg/engine/hosts_test.go +++ b/pkg/engine/hosts_test.go @@ -2,30 +2,41 @@ package engine import ( "os" + "os/exec" "path/filepath" + "runtime" "strings" "testing" + "time" ) -func TestHostsManager_AtomicApplyAndRollback(t *testing.T) { +func TestHostsManager_AtomicApplyDualStackAndRollback(t *testing.T) { tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + hostsPath := filepath.Join(tmpDir, "hosts") initialContent := "127.0.0.1 localhost\n::1 localhost\n" - if err := os.WriteFile(hostsPath, []byte(initialContent), 0644); err != nil { t.Fatalf("failed to create temp hosts: %v", err) } - manager := NewHostsManagerWithPath(hostsPath) - + manager := NewHostsManagerWithState(hostsPath, tmpDir) initialHash, err := manager.ComputeSHA256(hostsPath) if err != nil { t.Fatalf("failed to compute initial hash: %v", err) } - // Apply blocklist - domains := []string{"instagram.com", "tiktok.com"} - if err := manager.ApplyBlocklist(domains); err != nil { + now := time.Now().UTC() + meta := SessionMeta{ + SessionID: "sess-test-001", + PID: os.Getpid(), + StartedAt: now, + ExpectedEndAt: now.Add(25 * time.Minute), + Profile: "study", + } + + domains := []string{"https://www.Instagram.com/reels", "tiktok.com:443"} + if err := manager.ApplyBlocklistWithSession(domains, meta); err != nil { t.Fatalf("failed to apply blocklist: %v", err) } @@ -33,37 +44,299 @@ func TestHostsManager_AtomicApplyAndRollback(t *testing.T) { t.Fatalf("expected manager to report active") } + // Verify write-ahead journal fields + journal, err := manager.LoadJournal() + if err != nil { + t.Fatalf("expected journal to exist: %v", err) + } + if journal.OriginalSHA256 != initialHash { + t.Errorf("journal original_sha256 = %s, want %s", journal.OriginalSHA256, initialHash) + } + if journal.SessionID != "sess-test-001" || journal.Profile != "study" || journal.PID != os.Getpid() { + t.Errorf("unexpected journal metadata: %+v", journal) + } + modifiedData, err := os.ReadFile(hostsPath) if err != nil { t.Fatalf("failed to read modified hosts: %v", err) } modifiedStr := string(modifiedData) - if !strings.Contains(modifiedStr, "0.0.0.0 instagram.com") { - t.Errorf("expected 0.0.0.0 instagram.com in hosts") - } - if !strings.Contains(modifiedStr, "0.0.0.0 www.instagram.com") { - t.Errorf("expected 0.0.0.0 www.instagram.com in hosts") + expectedEntries := []string{ + MarkerBegin, + "0.0.0.0 instagram.com", + "0.0.0.0 www.instagram.com", + ":: instagram.com", + ":: www.instagram.com", + "0.0.0.0 tiktok.com", + "0.0.0.0 www.tiktok.com", + ":: tiktok.com", + ":: www.tiktok.com", + MarkerEnd, } - if !strings.Contains(modifiedStr, "0.0.0.0 tiktok.com") { - t.Errorf("expected 0.0.0.0 tiktok.com in hosts") + for _, entry := range expectedEntries { + if !strings.Contains(modifiedStr, entry) { + t.Errorf("expected %q in modified hosts, got:\n%s", entry, modifiedStr) + } } - // Rollback if err := manager.Rollback(); err != nil { t.Fatalf("failed to rollback: %v", err) } if manager.IsActive() { - t.Fatalf("expected manager to report inactive after rollback") + t.Fatalf("expected manager inactive after rollback") + } + if _, err := os.Stat(manager.JournalPath()); !os.IsNotExist(err) { + t.Errorf("expected journal removed after rollback") } restoredHash, err := manager.ComputeSHA256(hostsPath) if err != nil { t.Fatalf("failed to compute restored hash: %v", err) } - if initialHash != restoredHash { - t.Fatalf("restored hash %s does not match initial %s", restoredHash, initialHash) + t.Fatalf("restored hash %s != initial %s", restoredHash, initialHash) + } +} + +func TestHostsManager_NeverBackupContaminatedHosts(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + hostsPath := filepath.Join(tmpDir, "hosts") + cleanBase := "127.0.0.1 localhost\r\n192.168.1.20 devbox.lan\r\n" + contaminated := cleanBase + "\r\n" + + LegacyMarkerBegin + "\r\n127.0.0.1 youtube.com\r\n" + LegacyMarkerEnd + "\r\n\r\n" + + MarkerBegin + "\r\n0.0.0.0 reddit.com\r\n" + MarkerEnd + "\r\n" + + if err := os.WriteFile(hostsPath, []byte(contaminated), 0644); err != nil { + t.Fatalf("failed to write contaminated hosts: %v", err) + } + + manager := NewHostsManagerWithState(hostsPath, tmpDir) + if err := manager.ApplyBlocklist([]string{"x.com"}); err != nil { + t.Fatalf("ApplyBlocklist failed: %v", err) + } + + bakBytes, err := os.ReadFile(manager.BackupPath()) + if err != nil { + t.Fatalf("failed to read backup: %v", err) + } + if HasManagedMarkers(string(bakBytes)) { + t.Fatalf("backup file was contaminated with managed markers:\n%s", string(bakBytes)) + } + if string(bakBytes) != cleanBase { + t.Fatalf("backup %q != cleanBase %q", string(bakBytes), cleanBase) + } + + if err := manager.Rollback(); err != nil { + t.Fatalf("Rollback failed: %v", err) + } + restored, _ := os.ReadFile(hostsPath) + if string(restored) != cleanBase { + t.Fatalf("restored %q != cleanBase %q", string(restored), cleanBase) + } +} + +func TestStripManagedBlocks_MissingEndMarkerNoCorruption(t *testing.T) { + // Missing end marker on current block at EOF + truncatedCurrent := "127.0.0.1 localhost\n::1 localhost\n\n" + + MarkerBegin + "\n# FocusFlow v2.1 - Dual-Stack Managed Sinkhole\n0.0.0.0 youtube.com\n:: youtube.com\n" + got := StripManagedBlocks(truncatedCurrent) + want := "127.0.0.1 localhost\n::1 localhost\n" + if got != want { + t.Fatalf("truncated current strip got %q, want %q", got, want) + } + + // Missing end marker on legacy block followed by custom user entry + truncatedLegacyWithUserLine := "127.0.0.1 localhost\r\n\r\n" + + LegacyMarkerBegin + "\r\n127.0.0.1 instagram.com\r\n10.20.30.40 internal.corp\r\n" + got2 := StripManagedBlocks(truncatedLegacyWithUserLine) + want2 := "127.0.0.1 localhost\r\n10.20.30.40 internal.corp\r\n" + if got2 != want2 { + t.Fatalf("truncated legacy strip got %q, want %q", got2, want2) + } +} + +func TestHostsManager_RecoverIfOrphaned_DeadPIDAndFallback(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + hostsPath := filepath.Join(tmpDir, "hosts") + cleanContent := "127.0.0.1 localhost\n::1 localhost\n" + if err := os.WriteFile(hostsPath, []byte(cleanContent), 0644); err != nil { + t.Fatalf("write hosts: %v", err) + } + + manager := NewHostsManagerWithState(hostsPath, tmpDir) + now := time.Now().UTC() + + // Case 1: Live owning process (current PID) with future lease must NOT be clobbered + if err := manager.ApplyBlocklistWithSession([]string{"reddit.com"}, SessionMeta{ + SessionID: "live-sess", + PID: os.Getpid(), + StartedAt: now, + ExpectedEndAt: now.Add(30 * time.Minute), + Profile: "dev", + }); err != nil { + t.Fatalf("apply live: %v", err) + } + resLive, err := manager.RecoverIfOrphanedAt(now, nil) + if err != nil || resLive.Recovered { + t.Fatalf("expected live session not recovered, got res=%+v err=%v", resLive, err) + } + + // Case 2: Dead PID + tampered/missing backup falls back to deterministic marker stripping + deadMeta := SessionMeta{ + SessionID: "dead-sess-42", + PID: 99999999, + StartedAt: now.Add(-10 * time.Minute), + ExpectedEndAt: now.Add(15 * time.Minute), + Profile: "hardcore", + } + if err := manager.ApplyBlocklistWithSession([]string{"reddit.com", "twitch.tv"}, deadMeta); err != nil { + t.Fatalf("apply dead: %v", err) + } + // Tamper backup to force fallback path + if err := os.WriteFile(manager.BackupPath(), []byte("tampered-corrupt-backup"), 0644); err != nil { + t.Fatalf("tamper bak: %v", err) + } + + var markedOrphanID string + resDead, err := manager.RecoverIfOrphanedAt(now, func(sessionID string) { + markedOrphanID = sessionID + }) + if err != nil { + t.Fatalf("RecoverIfOrphanedAt failed: %v", err) + } + if !resDead.Recovered || !resDead.UsedFallback { + t.Fatalf("expected Recovered=true and UsedFallback=true, got %+v", resDead) + } + if markedOrphanID != "dead-sess-42" { + t.Errorf("expected orphan callback with 'dead-sess-42', got %q", markedOrphanID) + } + restored, _ := os.ReadFile(hostsPath) + if string(restored) != cleanContent { + t.Errorf("restored hosts %q != cleanContent %q", string(restored), cleanContent) + } +} + +func TestHostsManager_VerifyOrReapply_MidSessionTamper(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + hostsPath := filepath.Join(tmpDir, "hosts") + cleanContent := "127.0.0.1 localhost\n" + _ = os.WriteFile(hostsPath, []byte(cleanContent), 0644) + + manager := NewHostsManagerWithState(hostsPath, tmpDir) + meta := SessionMeta{ + SessionID: "watchdog-1", + PID: os.Getpid(), + StartedAt: time.Now().UTC(), + ExpectedEndAt: time.Now().UTC().Add(25 * time.Minute), + Profile: "hardcore", + } + domains := []string{"youtube.com", "tiktok.com"} + if err := manager.ApplyBlocklistWithSession(domains, meta); err != nil { + t.Fatalf("initial apply: %v", err) + } + + tampered, err := manager.VerifyOrReapply(domains, meta) + if err != nil || tampered { + t.Fatalf("expected untampered=false, got tampered=%v err=%v", tampered, err) + } + + // Simulate user deleting the managed block mid-sprint + _ = os.WriteFile(hostsPath, []byte(cleanContent), 0644) + tampered, err = manager.VerifyOrReapply(domains, meta) + if err != nil || !tampered { + t.Fatalf("expected tamper detected and re-applied, got tampered=%v err=%v", tampered, err) + } + if !manager.IsActive() { + t.Fatalf("expected blocklist active after VerifyOrReapply") + } + + // Ensure clean rollback still restores original clean hosts + if err := manager.Rollback(); err != nil { + t.Fatalf("rollback after tamper reapply failed: %v", err) + } + finalBytes, _ := os.ReadFile(hostsPath) + if string(finalBytes) != cleanContent { + t.Fatalf("final hosts %q != %q", string(finalBytes), cleanContent) + } +} + +func TestHostsManager_PermissionsAndACLPreservation(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + hostsPath := filepath.Join(tmpDir, "hosts") + if err := os.WriteFile(hostsPath, []byte("127.0.0.1 localhost\r\n"), 0644); err != nil { + t.Fatalf("write hosts: %v", err) + } + + if runtime.GOOS == "windows" { + // Grant explicit Users:(R) ACE and verify ReplaceFileW preserves it across Apply & Rollback + _ = exec.Command("icacls", hostsPath, "/grant", "*S-1-5-32-545:(R)").Run() + beforeOut, err := exec.Command("icacls", hostsPath).CombinedOutput() + if err != nil { + t.Skipf("icacls unavailable: %v", err) + } + + manager := NewHostsManagerWithState(hostsPath, tmpDir) + if err := manager.ApplyBlocklist([]string{"example.com"}); err != nil { + t.Fatalf("apply: %v", err) + } + afterOut, err := exec.Command("icacls", hostsPath).CombinedOutput() + if err != nil { + t.Fatalf("icacls after: %v", err) + } + if !strings.Contains(string(beforeOut), "(R)") || !strings.Contains(string(afterOut), "(R)") { + t.Logf("icacls before:\n%s\nafter:\n%s", string(beforeOut), string(afterOut)) + } + if string(beforeOut) != string(afterOut) { + t.Errorf("Windows DACL changed across atomic hosts update!\nbefore:\n%s\nafter:\n%s", string(beforeOut), string(afterOut)) + } + } else { + if err := os.Chmod(hostsPath, 0644); err != nil { + t.Fatalf("chmod: %v", err) + } + manager := NewHostsManagerWithState(hostsPath, tmpDir) + if err := manager.ApplyBlocklist([]string{"example.com"}); err != nil { + t.Fatalf("apply: %v", err) + } + info, err := os.Stat(hostsPath) + if err != nil { + t.Fatalf("stat: %v", err) + } + if info.Mode().Perm() != 0644 { + t.Errorf("expected POSIX perm 0644 preserved, got %o", info.Mode().Perm()) + } + } +} + +func TestDnsEngine_ExpandedDoHBypassDomains(t *testing.T) { + dns := &DnsEngine{} + got := dns.GetDoHBypassDomains() + required := []string{ + "cloudflare-dns.com", + "dns.google", + "dns.quad9.net", + "doh.opendns.com", + "dns.adguard-dns.com", + "dns.nextdns.io", + "doh.cleanbrowsing.org", + "doh.dns.sb", + "freedns.controld.com", + } + set := make(map[string]bool, len(got)) + for _, d := range got { + set[d] = true + } + for _, req := range required { + if !set[req] { + t.Errorf("missing required DoH domain %q", req) + } } } diff --git a/pkg/engine/process.go b/pkg/engine/process.go index d5d182b..f4bc8eb 100644 --- a/pkg/engine/process.go +++ b/pkg/engine/process.go @@ -1,6 +1,9 @@ package engine import ( + "bytes" + "os" + "path/filepath" "strings" ) @@ -15,17 +18,117 @@ func NewProcessSupervisor(blocked []string) *ProcessSupervisor { if trimmed == "" { continue } + if idx := strings.LastIndexAny(trimmed, `/\`); idx >= 0 { + trimmed = trimmed[idx+1:] + } + if trimmed == "" || IsProtectedProcess(trimmed) { + continue + } m[trimmed] = struct{}{} - // Support cross-platform matching with and without .exe if strings.HasSuffix(trimmed, ".exe") { - m[strings.TrimSuffix(trimmed, ".exe")] = struct{}{} + base := strings.TrimSuffix(trimmed, ".exe") + if base != "" && !IsProtectedProcess(base) { + m[base] = struct{}{} + } } else { - m[trimmed+".exe"] = struct{}{} + withExe := trimmed + ".exe" + if !IsProtectedProcess(withExe) { + m[withExe] = struct{}{} + } } } return &ProcessSupervisor{blockedNames: m} } +func isProtectedPID(pid int) bool { + if pid <= 4 { + return true + } + if pid == os.Getpid() || pid == os.Getppid() { + return true + } + return false +} + +func cleanBasename(pathOrName string) string { + s := strings.TrimSpace(pathOrName) + if s == "" { + return "" + } + if idx := strings.LastIndexAny(s, `/\`); idx >= 0 { + s = s[idx+1:] + } + return s +} + +func (p *ProcessSupervisor) shouldTerminateProcess(pid int, candidateNames ...string) (string, bool) { + if isProtectedPID(pid) || len(p.blockedNames) == 0 { + return "", false + } + for _, cand := range candidateNames { + base := cleanBasename(cand) + if base == "" { + continue + } + if IsProtectedProcess(base) { + return "", false + } + } + for _, cand := range candidateNames { + base := cleanBasename(cand) + if base == "" { + continue + } + lower := strings.ToLower(base) + if _, exists := p.blockedNames[lower]; exists { + return base, true + } + } + return "", false +} + +// resolveProcFSNames resolves process executable candidate names from a Linux /proc/ entry. +// When /proc//comm hits the 15-byte Linux TASK_COMM_LEN truncation limit (or is unreadable), +// it also resolves /proc//exe symlink target and /proc//cmdline argv[0] basename. +func resolveProcFSNames(procRoot string, pidStr string) []string { + var candidates []string + pidDir := filepath.Join(procRoot, pidStr) + + commBytes, commErr := os.ReadFile(filepath.Join(pidDir, "comm")) + var commName string + if commErr == nil { + commName = strings.TrimSpace(string(commBytes)) + if commName != "" { + candidates = append(candidates, commName) + } + } + + // Linux kernel TASK_COMM_LEN is 16 bytes (max 15 visible chars in /proc//comm). + if commName == "" || len(commName) >= 15 { + if exeTarget, err := os.Readlink(filepath.Join(pidDir, "exe")); err == nil { + exeTarget = strings.TrimSuffix(exeTarget, " (deleted)") + if base := cleanBasename(exeTarget); base != "" { + candidates = append(candidates, base) + } + } + if cmdBytes, err := os.ReadFile(filepath.Join(pidDir, "cmdline")); err == nil && len(cmdBytes) > 0 { + argv0 := cmdBytes + if nulIdx := bytes.IndexByte(cmdBytes, 0); nulIdx >= 0 { + argv0 = cmdBytes[:nulIdx] + } + argStr := strings.TrimSpace(string(argv0)) + if argStr != "" { + // Handle Wine / proton style Windows paths or POSIX paths in cmdline + if base := cleanBasename(argStr); base != "" { + candidates = append(candidates, base) + } + } + } + } + + return candidates +} + // KillProcessesByNames terminates running processes matching any of the specified names. func KillProcessesByNames(names []string) error { sup := NewProcessSupervisor(names) diff --git a/pkg/engine/process_posix.go b/pkg/engine/process_posix.go index 73cce9f..6d81e21 100644 --- a/pkg/engine/process_posix.go +++ b/pkg/engine/process_posix.go @@ -8,89 +8,66 @@ import ( "fmt" "os" "os/exec" - "path/filepath" "strconv" "strings" "syscall" ) -// ScanAndTerminate scans active processes on POSIX systems (Linux via /proc, or macOS/BSD via ps), -// terminating any process whose name matches the supervisor's blocklist with SIGTERM. +// ScanAndTerminate scans active processes on POSIX systems (Linux via /proc without spawning +// subprocesses, or macOS/BSD via ps when /proc is unavailable), terminating matching targets with SIGTERM. func (p *ProcessSupervisor) ScanAndTerminate() []string { var terminated []string if len(p.blockedNames) == 0 { return terminated } - // Strategy 1: Linux /proc scanning (efficient and direct) - if _, err := os.Stat("/proc"); err == nil { - procMatches := p.scanProcDir() - if len(procMatches) > 0 { - return procMatches - } - } - - // Strategy 2: Standard POSIX `ps` tool (macOS, BSD, and Linux fallback) - psMatches := p.scanPsOutput() - if len(psMatches) > 0 { - return psMatches + // Strategy 1: Linux /proc scanning — if /proc is mounted and has PID directories, + // return directly even when 0 matches occur (never spawn `ps` every tick on Linux!). + if procMatches, procAvailable := p.scanProcDir("/proc"); procAvailable { + return procMatches } - return terminated + // Strategy 2: Standard POSIX `ps` fallback for macOS / BSD + return p.scanPsOutput() } -func (p *ProcessSupervisor) scanProcDir() []string { +func (p *ProcessSupervisor) scanProcDir(procRoot string) ([]string, bool) { var terminated []string - entries, err := os.ReadDir("/proc") + entries, err := os.ReadDir(procRoot) if err != nil { - return terminated + return nil, false } + sawPID := false for _, entry := range entries { if !entry.IsDir() { continue } pid, err := strconv.Atoi(entry.Name()) - if err != nil || pid <= 1 { - continue // skip non-numeric dirs and init process - } - - // Read /proc//comm (process name) - commPath := filepath.Join("/proc", entry.Name(), "comm") - commBytes, err := os.ReadFile(commPath) - var procName string - if err == nil { - procName = strings.TrimSpace(string(commBytes)) - } else { - // Fallback: check /proc//exe symbolic link target - exePath := filepath.Join("/proc", entry.Name(), "exe") - target, err := os.Readlink(exePath) - if err == nil { - procName = filepath.Base(target) - } + if err != nil { + continue } - - if procName == "" { + sawPID = true + if isProtectedPID(pid) { continue } - procLower := strings.ToLower(procName) - if _, exists := p.blockedNames[procLower]; exists { - proc, err := os.FindProcess(pid) - if err == nil { + candidates := resolveProcFSNames(procRoot, entry.Name()) + if matchedName, ok := p.shouldTerminateProcess(pid, candidates...); ok { + if proc, err := os.FindProcess(pid); err == nil { if err := proc.Signal(syscall.SIGTERM); err == nil { - terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", procName, pid)) + terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", matchedName, pid)) } } } } - return terminated + return terminated, sawPID } func (p *ProcessSupervisor) scanPsOutput() []string { var terminated []string - cmd := exec.Command("ps", "-A", "-o", "pid,comm") + cmd := exec.Command("ps", "-A", "-o", "pid=,comm=") out, err := cmd.Output() if err != nil { return terminated @@ -109,19 +86,15 @@ func (p *ProcessSupervisor) scanPsOutput() []string { } pid, err := strconv.Atoi(fields[0]) - if err != nil || pid <= 1 { + if err != nil || isProtectedPID(pid) { continue } fullComm := strings.Join(fields[1:], " ") - procName := filepath.Base(fullComm) - procLower := strings.ToLower(procName) - - if _, exists := p.blockedNames[procLower]; exists { - proc, err := os.FindProcess(pid) - if err == nil { + if matchedName, ok := p.shouldTerminateProcess(pid, fullComm); ok { + if proc, err := os.FindProcess(pid); err == nil { if err := proc.Signal(syscall.SIGTERM); err == nil { - terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", procName, pid)) + terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", matchedName, pid)) } } } diff --git a/pkg/engine/process_test.go b/pkg/engine/process_test.go index f569592..d7d6fd4 100644 --- a/pkg/engine/process_test.go +++ b/pkg/engine/process_test.go @@ -1,38 +1,97 @@ package engine import ( + "os" + "path/filepath" "testing" ) -func TestProcessSupervisor_Normalization(t *testing.T) { - blocked := []string{"Discord.exe", "spotify", " STEAM.EXE "} +func TestProcessSupervisor_NormalizationAndDenylist(t *testing.T) { + blocked := []string{"Discord.exe", "spotify", " STEAM.EXE ", "explorer.exe", "lsass.exe", "python.exe", "focusflow.exe"} sup := NewProcessSupervisor(blocked) - expectedKeys := []string{"discord.exe", "discord", "spotify", "spotify.exe", "steam.exe", "steam"} - for _, key := range expectedKeys { + expectedAllowed := []string{"discord.exe", "discord", "spotify", "spotify.exe", "steam.exe", "steam"} + for _, key := range expectedAllowed { if _, exists := sup.blockedNames[key]; !exists { t.Errorf("expected %q to be in blockedNames map", key) } } + + forbidden := []string{"explorer.exe", "explorer", "lsass.exe", "lsass", "python.exe", "python", "focusflow.exe", "focusflow"} + for _, key := range forbidden { + if _, exists := sup.blockedNames[key]; exists { + t.Errorf("protected binary %q must never enter blockedNames", key) + } + } } -func TestProcessSupervisor_ScanAndTerminate_Empty(t *testing.T) { - sup := NewProcessSupervisor(nil) - terminated := sup.ScanAndTerminate() - if len(terminated) != 0 { - t.Errorf("expected 0 terminated processes for empty supervisor, got %d", len(terminated)) +func TestProcessSupervisor_ProtectedPIDsNeverTerminated(t *testing.T) { + sup := NewProcessSupervisor([]string{"discord.exe"}) + + for _, pid := range []int{0, 1, 4, os.Getpid(), os.Getppid()} { + if _, ok := sup.shouldTerminateProcess(pid, "discord.exe"); ok { + t.Errorf("protected PID %d should never be approved for termination", pid) + } } - err := KillProcessesByNames(nil) - if err != nil { - t.Errorf("expected nil error for empty KillProcessesByNames, got %v", err) + if matched, ok := sup.shouldTerminateProcess(424242, "discord.exe"); !ok || matched != "discord.exe" { + t.Errorf("expected normal PID 424242 discord.exe to match, got (%q, %v)", matched, ok) + } + if _, ok := sup.shouldTerminateProcess(424242, "svchost.exe"); ok { + t.Errorf("svchost.exe must never match") } } -func TestProcessSupervisor_ScanAndTerminate_NonExistent(t *testing.T) { - sup := NewProcessSupervisor([]string{"nonexistent_process_123456789.exe"}) - terminated := sup.ScanAndTerminate() - if len(terminated) != 0 { - t.Errorf("expected 0 terminated processes for nonexistent process, got %d", len(terminated)) +func TestResolveProcFSNames_Linux15ByteCommTruncation(t *testing.T) { + fakeProc := t.TempDir() + pidDir := filepath.Join(fakeProc, "12345") + if err := os.MkdirAll(pidDir, 0755); err != nil { + t.Fatalf("mkdir: %v", err) + } + + // Simulate Linux 15-byte TASK_COMM_LEN truncation for "epicgameslauncher" -> "epicgameslaunch" + if err := os.WriteFile(filepath.Join(pidDir, "comm"), []byte("epicgameslaunch\n"), 0644); err != nil { + t.Fatalf("write comm: %v", err) + } + cmdline := "/opt/games/epicgameslauncher\x00--silent\x00" + if err := os.WriteFile(filepath.Join(pidDir, "cmdline"), []byte(cmdline), 0644); err != nil { + t.Fatalf("write cmdline: %v", err) + } + + candidates := resolveProcFSNames(fakeProc, "12345") + sup := NewProcessSupervisor([]string{"epicgameslauncher.exe"}) + matched, ok := sup.shouldTerminateProcess(12345, candidates...) + if !ok || matched != "epicgameslauncher" { + t.Fatalf("expected truncated comm to resolve full binary via cmdline, got candidates=%v matched=%q ok=%v", + candidates, matched, ok) + } +} + +func TestAntiCheatGuard_IncludesSystemInformer(t *testing.T) { + ac := NewAntiCheatGuard(StrictnessHardcore) + for _, bin := range []string{"taskmgr.exe", "processhacker.exe", "systeminformer.exe", "procmon.exe", "procexp.exe"} { + if _, exists := ac.supervisor.blockedNames[bin]; !exists { + t.Errorf("expected %q in hardcore AntiCheatGuard", bin) + } + } + + relaxed := NewAntiCheatGuard(StrictnessRelaxed) + if len(relaxed.supervisor.blockedNames) != 0 { + t.Errorf("expected empty anti-cheat blocklist in relaxed mode") + } +} + +func TestProcessSupervisor_ScanAndTerminate_EmptyAndNonExistent(t *testing.T) { + sup := NewProcessSupervisor(nil) + if got := sup.ScanAndTerminate(); len(got) != 0 { + t.Errorf("expected 0 terminated for empty supervisor, got %d", len(got)) + } + if err := KillProcessesByNames(nil); err != nil { + t.Errorf("unexpected error: %v", err) + } + + sup2 := NewProcessSupervisor([]string{"nonexistent_focusflow_test_proc_987654.exe"}) + if got := sup2.ScanAndTerminate(); len(got) != 0 { + t.Errorf("expected 0 terminated for nonexistent process, got %d", len(got)) } } diff --git a/pkg/engine/process_windows.go b/pkg/engine/process_windows.go index 5ae2703..2c7d044 100644 --- a/pkg/engine/process_windows.go +++ b/pkg/engine/process_windows.go @@ -4,13 +4,12 @@ package engine import ( "fmt" - "strings" "syscall" "unsafe" ) // ScanAndTerminate scans active Windows processes via Toolhelp32 snapshot, -// terminating any process whose executable name matches the supervisor's blocklist. +// terminating any non-protected process whose executable name matches the blocklist. func (p *ProcessSupervisor) ScanAndTerminate() []string { var terminated []string if len(p.blockedNames) == 0 { @@ -31,16 +30,16 @@ func (p *ProcessSupervisor) ScanAndTerminate() []string { } for { + pid := int(entry.ProcessID) exeName := syscall.UTF16ToString(entry.ExeFile[:]) - exeLower := strings.ToLower(exeName) - if _, exists := p.blockedNames[exeLower]; exists { + if matchedName, ok := p.shouldTerminateProcess(pid, exeName); ok { hProc, err := syscall.OpenProcess(syscall.PROCESS_TERMINATE, false, entry.ProcessID) if err == nil && hProc != 0 { if err := syscall.TerminateProcess(hProc, 1); err == nil { - terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", exeName, entry.ProcessID)) + terminated = append(terminated, fmt.Sprintf("%s (PID: %d)", matchedName, entry.ProcessID)) } - syscall.CloseHandle(hProc) + _ = syscall.CloseHandle(hProc) } } diff --git a/pkg/engine/sanitize.go b/pkg/engine/sanitize.go new file mode 100644 index 0000000..f3beaeb --- /dev/null +++ b/pkg/engine/sanitize.go @@ -0,0 +1,279 @@ +package engine + +import ( + "errors" + "fmt" + "net" + "strconv" + "strings" +) + +var ( + ErrEmptyDomain = errors.New("domain cannot be empty") + ErrControlChars = errors.New("domain contains illegal control or whitespace characters") + ErrIPLiteral = errors.New("IP literals cannot be added to hosts blocklist") + ErrReservedDomain = errors.New("reserved or local domain cannot be blocked") + ErrInvalidRFC1123 = errors.New("invalid RFC-1123 domain format") + ErrEmptyProcess = errors.New("process name cannot be empty") + ErrInvalidProcess = errors.New("invalid process executable name") + ErrProtectedBinary = errors.New("protected system or host process cannot be blocked") +) + +var reservedExactDomains = map[string]struct{}{ + "localhost": {}, + "localhost.localdomain": {}, + "localdomain": {}, + "local": {}, + "broadcasthost": {}, + "ip6-localhost": {}, + "ip6-loopback": {}, + "ip6-localnet": {}, + "ip6-mcastprefix": {}, + "ip6-allnodes": {}, + "ip6-allrouters": {}, + "ip6-allhosts": {}, +} + +var protectedBaseNames = []string{ + "csrss", + "smss", + "lsass", + "services", + "svchost", + "wininit", + "winlogon", + "dwm", + "explorer", + "sihost", + "fontdrvhost", + "focusflow", + "python", + "python3", + "pythonw", + "conhost", + "wt", + "init", + "systemd", + "launchd", + "kernel_task", +} + +var protectedProcessMap = func() map[string]struct{} { + m := make(map[string]struct{}, len(protectedBaseNames)*2) + for _, base := range protectedBaseNames { + lower := strings.ToLower(base) + m[lower] = struct{}{} + m[lower+".exe"] = struct{}{} + } + return m +}() + +// ProtectedProcessNames returns the canonical protected Windows/host executable names. +func ProtectedProcessNames() []string { + out := make([]string, 0, len(protectedBaseNames)) + for _, b := range protectedBaseNames { + out = append(out, b+".exe") + } + return out +} + +// IsProtectedProcess reports whether a process name belongs to the critical system/host denylist. +func IsProtectedProcess(name string) bool { + cleaned := strings.ToLower(strings.TrimSpace(name)) + if cleaned == "" { + return false + } + // Extract basename if any path separators exist + if idx := strings.LastIndexAny(cleaned, `/\`); idx >= 0 { + cleaned = cleaned[idx+1:] + } + _, exists := protectedProcessMap[cleaned] + return exists +} + +// NormalizeProcessName validates and normalizes an executable name for custom blocklists. +func NormalizeProcessName(raw string) (string, error) { + for i := 0; i < len(raw); i++ { + c := raw[i] + if c < 0x20 || c == 0x7f { + return "", ErrInvalidProcess + } + } + trimmed := strings.ToLower(strings.TrimSpace(raw)) + if trimmed == "" { + return "", ErrEmptyProcess + } + if strings.ContainsAny(trimmed, `/\:*?"<>| `) || strings.Contains(trimmed, "..") { + return "", ErrInvalidProcess + } + if IsProtectedProcess(trimmed) { + return "", fmt.Errorf("%w: %s", ErrProtectedBinary, trimmed) + } + if !strings.HasSuffix(trimmed, ".exe") { + trimmed += ".exe" + } + if IsProtectedProcess(trimmed) { + return "", fmt.Errorf("%w: %s", ErrProtectedBinary, trimmed) + } + base := strings.TrimSuffix(trimmed, ".exe") + if base == "" { + return "", ErrInvalidProcess + } + return trimmed, nil +} + +// SanitizeDomain strictly normalizes and validates a domain name per RFC-1123. +// Strips http(s)://, paths, query strings, fragments, valid ports, outer spaces, and leading www. +// Rejects newlines, control chars, embedded whitespace, IPv4/IPv6 literals, localhost, localdomain, and *.local. +func SanitizeDomain(raw string) (string, error) { + for i := 0; i < len(raw); i++ { + c := raw[i] + if c < 0x20 || c == 0x7f { + return "", ErrControlChars + } + } + + s := strings.Trim(raw, " ") + if s == "" || strings.HasPrefix(s, "#") { + return "", ErrEmptyDomain + } + if strings.ContainsAny(s, " \t\r\n") { + return "", ErrControlChars + } + + s = strings.ToLower(s) + + if strings.HasPrefix(s, "https://") { + s = strings.TrimPrefix(s, "https://") + } else if strings.HasPrefix(s, "http://") { + s = strings.TrimPrefix(s, "http://") + } else if strings.Contains(s, "://") { + return "", ErrInvalidRFC1123 + } + + // Strip path, query, fragment + if idx := strings.IndexAny(s, "/?#"); idx >= 0 { + s = s[:idx] + } + if s == "" { + return "", ErrEmptyDomain + } + + // Reject userinfo or bracketed IPv6 literals + if strings.Contains(s, "@") || strings.ContainsAny(s, "[]") { + if strings.ContainsAny(s, "[]") { + return "", ErrIPLiteral + } + return "", ErrInvalidRFC1123 + } + + // Handle port vs IPv6 colons + if colonCount := strings.Count(s, ":"); colonCount > 1 { + return "", ErrIPLiteral + } else if colonCount == 1 { + idx := strings.IndexByte(s, ':') + hostPart := s[:idx] + portPart := s[idx+1:] + if portPart == "" { + return "", ErrInvalidRFC1123 + } + portNum, err := strconv.Atoi(portPart) + if err != nil || portNum < 1 || portNum > 65535 { + return "", ErrInvalidRFC1123 + } + s = hostPart + } + + // Strip single trailing FQDN dot if present + s = strings.TrimSuffix(s, ".") + if s == "" { + return "", ErrEmptyDomain + } + + // Reject IPv4/IPv6 literals before and after stripping www. + if net.ParseIP(s) != nil { + return "", ErrIPLiteral + } + + if _, reserved := reservedExactDomains[s]; reserved { + return "", ErrReservedDomain + } + if strings.HasSuffix(s, ".local") || strings.HasSuffix(s, ".localhost") || strings.HasSuffix(s, ".localdomain") { + return "", ErrReservedDomain + } + + if strings.HasPrefix(s, "www.") { + rest := strings.TrimPrefix(s, "www.") + if strings.Contains(rest, ".") { + s = rest + } + } + + if _, reserved := reservedExactDomains[s]; reserved { + return "", ErrReservedDomain + } + if strings.HasSuffix(s, ".local") || strings.HasSuffix(s, ".localhost") || strings.HasSuffix(s, ".localdomain") { + return "", ErrReservedDomain + } + if net.ParseIP(s) != nil { + return "", ErrIPLiteral + } + + if len(s) > 253 || !strings.Contains(s, ".") { + return "", ErrInvalidRFC1123 + } + + labels := strings.Split(s, ".") + if len(labels) < 2 { + return "", ErrInvalidRFC1123 + } + + for _, label := range labels { + if len(label) < 1 || len(label) > 63 { + return "", ErrInvalidRFC1123 + } + if label[0] == '-' || label[len(label)-1] == '-' { + return "", ErrInvalidRFC1123 + } + for i := 0; i < len(label); i++ { + ch := label[i] + isLower := ch >= 'a' && ch <= 'z' + isDigit := ch >= '0' && ch <= '9' + if !isLower && !isDigit && ch != '-' { + return "", ErrInvalidRFC1123 + } + } + } + + // RFC-1123 / DNS rule: top-level label cannot be all digits (also rejects malformed numeric IPs like 999.999.999.999) + tld := labels[len(labels)-1] + allDigits := true + for i := 0; i < len(tld); i++ { + if tld[i] < '0' || tld[i] > '9' { + allDigits = false + break + } + } + if allDigits { + return "", ErrIPLiteral + } + + return s, nil +} + +// SanitizeDomains filters, canonicalizes, and deduplicates a list of domains while preserving order. +func SanitizeDomains(domains []string) []string { + seen := make(map[string]struct{}, len(domains)) + out := make([]string, 0, len(domains)) + for _, raw := range domains { + clean, err := SanitizeDomain(raw) + if err != nil { + continue + } + if _, exists := seen[clean]; !exists { + seen[clean] = struct{}{} + out = append(out, clean) + } + } + return out +} diff --git a/pkg/engine/sanitize_test.go b/pkg/engine/sanitize_test.go new file mode 100644 index 0000000..b4f2481 --- /dev/null +++ b/pkg/engine/sanitize_test.go @@ -0,0 +1,92 @@ +package engine + +import "testing" + +func TestSanitizeDomain_ValidInputs(t *testing.T) { + cases := []struct { + raw string + want string + }{ + {"youtube.com", "youtube.com"}, + {" HTTPS://www.YouTube.com:443/watch?v=dQw4w9WgXcQ#top ", "youtube.com"}, + {"http://Sub.Reddit.com:8080/r/golang/", "sub.reddit.com"}, + {"x.com.", "x.com"}, + {"dns.adguard-dns.com", "dns.adguard-dns.com"}, + {"one.one.one.one", "one.one.one.one"}, + } + + for _, tc := range cases { + got, err := SanitizeDomain(tc.raw) + if err != nil { + t.Errorf("SanitizeDomain(%q) unexpected error: %v", tc.raw, err) + continue + } + if got != tc.want { + t.Errorf("SanitizeDomain(%q) = %q, want %q", tc.raw, got, tc.want) + } + } +} + +func TestSanitizeDomain_RejectsMaliciousAndReservedInputs(t *testing.T) { + badInputs := []string{ + "", + " ", + "# comment", + "evil.com\n127.0.0.1 bank.com", + "evil.com\r\n0.0.0.0 github.com", + "evil.com\tinjected.com", + "evil.com injected.com", + "evil\x00.com", + "127.0.0.1", + "0.0.0.0", + "192.168.1.1", + "999.999.999.999", + "::1", + "[::1]:8080", + "2001:db8::1", + "localhost", + "LOCALHOST", + "localdomain", + "localhost.localdomain", + "printer.local", + "sub.localhost", + "dev.localdomain", + "singlelabel", + "-badlabel.com", + "badlabel-.com", + "bad..dots.com", + "example.com:99999", + "example.com:notaport", + "ftp://example.com", + "user@example.com", + } + + for _, raw := range badInputs { + if got, err := SanitizeDomain(raw); err == nil { + t.Errorf("SanitizeDomain(%q) succeeded with %q; expected rejection", raw, got) + } + } +} + +func TestProtectedProcesses_DenylistEnforcement(t *testing.T) { + protected := []string{ + "csrss.exe", "smss.exe", "lsass.exe", "services.exe", "svchost.exe", + "wininit.exe", "winlogon.exe", "dwm.exe", "explorer.exe", "sihost.exe", + "fontdrvhost.exe", "focusflow.exe", "python.exe", "pythonw.exe", + "conhost.exe", "wt.exe", "EXPLORER", "PythonW", `C:\Windows\System32\lsass.exe`, + } + + for _, name := range protected { + if !IsProtectedProcess(name) { + t.Errorf("expected IsProtectedProcess(%q) == true", name) + } + if got, err := NormalizeProcessName(name); err == nil { + t.Errorf("expected NormalizeProcessName(%q) to fail, got %q", name, got) + } + } + + valid, err := NormalizeProcessName(" Discord ") + if err != nil || valid != "discord.exe" { + t.Fatalf("expected NormalizeProcessName('Discord') == 'discord.exe', got %q (err=%v)", valid, err) + } +} diff --git a/pkg/profile/profiles.go b/pkg/profile/profiles.go index b847535..9711473 100644 --- a/pkg/profile/profiles.go +++ b/pkg/profile/profiles.go @@ -5,6 +5,9 @@ import ( "os" "path/filepath" "strings" + + "github.com/aloneangel45/focusflow/pkg/engine" + "github.com/aloneangel45/focusflow/pkg/storage" ) type FocusProfile struct { @@ -22,40 +25,79 @@ type ConfigStore struct { Profiles map[string]*FocusProfile `json:"profiles"` } +type rawConfigCompat struct { + CustomDomains []string `json:"custom_domains"` + CustomProcesses []string `json:"custom_processes"` + CustomSites []string `json:"custom_sites"` + CustomApps []string `json:"custom_apps"` + Profiles map[string]*FocusProfile `json:"profiles"` +} + func GetConfigDir() string { - appData := os.Getenv("APPDATA") - if appData != "" { - return filepath.Join(appData, "FocusFlow") - } - return ".focusflow" + return storage.GetStateDir() } func GetConfigPath() string { return filepath.Join(GetConfigDir(), "config.json") } +func DefaultProfiles() map[string]*FocusProfile { + return map[string]*FocusProfile{ + "dev": DevProfile(), + "study": StudyProfile(), + "hardcore": HardcoreProfile(), + } +} + +func sanitizeProcessList(procs []string) []string { + seen := make(map[string]struct{}, len(procs)) + out := make([]string, 0, len(procs)) + for _, raw := range procs { + norm, err := engine.NormalizeProcessName(raw) + if err != nil { + continue + } + if _, exists := seen[norm]; !exists { + seen[norm] = struct{}{} + out = append(out, norm) + } + } + return out +} + func LoadConfig() (*ConfigStore, error) { path := GetConfigPath() data, err := os.ReadFile(path) if err != nil { - // Return default config - cfg := &ConfigStore{ - CustomDomains: []string{}, - CustomProcesses: []string{}, - Profiles: map[string]*FocusProfile{ - "dev": DevProfile(), - "study": StudyProfile(), - "hardcore": HardcoreProfile(), - }, + if os.IsNotExist(err) { + cfg := &ConfigStore{ + CustomDomains: []string{}, + CustomProcesses: []string{}, + Profiles: DefaultProfiles(), + } + _ = SaveConfig(cfg) + return cfg, nil } - _ = SaveConfig(cfg) - return cfg, nil + return nil, err } - var cfg ConfigStore - if err := json.Unmarshal(data, &cfg); err != nil { + var compat rawConfigCompat + if err := json.Unmarshal(data, &compat); err != nil { return nil, err } + + mergedDomains := append([]string{}, compat.CustomDomains...) + mergedDomains = append(mergedDomains, compat.CustomSites...) + + mergedProcs := append([]string{}, compat.CustomProcesses...) + mergedProcs = append(mergedProcs, compat.CustomApps...) + + cfg := &ConfigStore{ + CustomDomains: engine.SanitizeDomains(mergedDomains), + CustomProcesses: sanitizeProcessList(mergedProcs), + Profiles: compat.Profiles, + } + if cfg.Profiles == nil { cfg.Profiles = make(map[string]*FocusProfile) } @@ -68,18 +110,72 @@ func LoadConfig() (*ConfigStore, error) { if _, ok := cfg.Profiles["hardcore"]; !ok { cfg.Profiles["hardcore"] = HardcoreProfile() } - return &cfg, nil + + for key, p := range cfg.Profiles { + if p == nil { + continue + } + if p.Name == "" { + p.Name = key + } + p.BlockedDomains = engine.SanitizeDomains(p.BlockedDomains) + p.BlockedProcesses = sanitizeProcessList(p.BlockedProcesses) + } + + return cfg, nil } func SaveConfig(cfg *ConfigStore) error { dir := GetConfigDir() - _ = os.MkdirAll(dir, 0755) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + + if cfg.CustomDomains == nil { + cfg.CustomDomains = []string{} + } else { + cfg.CustomDomains = engine.SanitizeDomains(cfg.CustomDomains) + } + if cfg.CustomProcesses == nil { + cfg.CustomProcesses = []string{} + } else { + cfg.CustomProcesses = sanitizeProcessList(cfg.CustomProcesses) + } + if cfg.Profiles == nil { + cfg.Profiles = DefaultProfiles() + } data, err := json.MarshalIndent(cfg, "", " ") if err != nil { return err } - return os.WriteFile(GetConfigPath(), data, 0644) + data = append(data, '\n') + + cfgPath := GetConfigPath() + tmpFile, err := os.CreateTemp(dir, "config-*.tmp") + if err != nil { + return err + } + tmpPath := tmpFile.Name() + if _, err := tmpFile.Write(data); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + _ = tmpFile.Sync() + if err := tmpFile.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Chmod(tmpPath, 0644) + if err := os.Rename(tmpPath, cfgPath); err != nil { + if wErr := os.WriteFile(cfgPath, data, 0644); wErr != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Remove(tmpPath) + } + return nil } func DevProfile() *FocusProfile { @@ -111,7 +207,7 @@ func DevProfile() *FocusProfile { func StudyProfile() *FocusProfile { return &FocusProfile{ Name: "study", - Description: "Academic & Exam Preparation Mode (YKS/KPSS/LGS - Zero entertainment)", + Description: "Academic & Exam Preparation Mode (Zero entertainment)", BlockedDomains: []string{ "youtube.com", "instagram.com", @@ -147,24 +243,41 @@ func HardcoreProfile() *FocusProfile { } func LoadOrDefault(name string) *FocusProfile { + lower := strings.ToLower(strings.TrimSpace(name)) + if lower == "coding" { + lower = "dev" + } else if lower == "lockdown" { + lower = "hardcore" + } + cfg, err := LoadConfig() if err == nil { - lower := strings.ToLower(strings.TrimSpace(name)) - if p, ok := cfg.Profiles[lower]; ok { - // Merge global custom domains & processes + if p, ok := cfg.Profiles[lower]; ok && p != nil { pCopy := *p - pCopy.BlockedDomains = append(pCopy.BlockedDomains, cfg.CustomDomains...) - pCopy.BlockedProcesses = append(pCopy.BlockedProcesses, cfg.CustomProcesses...) + domains := append([]string{}, p.BlockedDomains...) + domains = append(domains, cfg.CustomDomains...) + pCopy.BlockedDomains = engine.SanitizeDomains(domains) + + procs := append([]string{}, p.BlockedProcesses...) + procs = append(procs, cfg.CustomProcesses...) + pCopy.BlockedProcesses = sanitizeProcessList(procs) return &pCopy } } - switch strings.ToLower(strings.TrimSpace(name)) { - case "dev", "coding": - return DevProfile() - case "hardcore", "lockdown": - return HardcoreProfile() + var fallback *FocusProfile + switch lower { + case "dev": + fallback = DevProfile() + case "hardcore": + fallback = HardcoreProfile() default: - return StudyProfile() + fallback = StudyProfile() + } + + if err == nil { + fallback.BlockedDomains = engine.SanitizeDomains(append(fallback.BlockedDomains, cfg.CustomDomains...)) + fallback.BlockedProcesses = sanitizeProcessList(append(fallback.BlockedProcesses, cfg.CustomProcesses...)) } + return fallback } diff --git a/pkg/profile/profiles_test.go b/pkg/profile/profiles_test.go index b217c81..64f40c6 100644 --- a/pkg/profile/profiles_test.go +++ b/pkg/profile/profiles_test.go @@ -1,19 +1,27 @@ package profile -import "testing" +import ( + "os" + "path/filepath" + "testing" +) -func TestProfiles_Defaults(t *testing.T) { - dev := DevProfile() - if dev.Name != "dev" { - t.Errorf("expected dev name, got %s", dev.Name) +func TestProfiles_DefaultsAndHermeticConfig(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + if GetConfigDir() != filepath.Clean(tmpDir) { + t.Fatalf("GetConfigDir() = %q, want %q", GetConfigDir(), filepath.Clean(tmpDir)) } - if len(dev.BlockedDomains) == 0 { - t.Errorf("expected blocked domains in dev profile") + + dev := DevProfile() + if dev.Name != "dev" || len(dev.BlockedDomains) == 0 { + t.Errorf("unexpected dev profile: %+v", dev) } study := StudyProfile() - if study.Name != "study" { - t.Errorf("expected study name, got %s", study.Name) + if study.Name != "study" || study.DefaultWorkMinutes != 25 { + t.Errorf("unexpected study profile: %+v", study) } hardcore := HardcoreProfile() @@ -26,3 +34,38 @@ func TestProfiles_Defaults(t *testing.T) { t.Errorf("expected fallback to study, got %s", fallback.Name) } } + +func TestProfiles_LegacyMigrationAndDenylistSanitization(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + legacyJSON := `{ + "custom_sites": ["https://www.ExampleDistraction.com/feed", "127.0.0.1", "localhost"], + "custom_apps": ["Battle.net", "explorer.exe", "python.exe"] +}` + if err := os.WriteFile(GetConfigPath(), []byte(legacyJSON), 0644); err != nil { + t.Fatalf("write config: %v", err) + } + + cfg, err := LoadConfig() + if err != nil { + t.Fatalf("LoadConfig failed: %v", err) + } + if len(cfg.CustomDomains) != 1 || cfg.CustomDomains[0] != "exampledistraction.com" { + t.Fatalf("unexpected sanitized CustomDomains: %v", cfg.CustomDomains) + } + if len(cfg.CustomProcesses) != 1 || cfg.CustomProcesses[0] != "battle.net.exe" { + t.Fatalf("unexpected sanitized CustomProcesses: %v", cfg.CustomProcesses) + } + + merged := LoadOrDefault("dev") + foundDomain := false + for _, d := range merged.BlockedDomains { + if d == "exampledistraction.com" { + foundDomain = true + } + } + if !foundDomain { + t.Errorf("expected custom domain merged into dev profile") + } +} diff --git a/pkg/storage/store.go b/pkg/storage/store.go index 7dbeab0..b8b5ea5 100644 --- a/pkg/storage/store.go +++ b/pkg/storage/store.go @@ -1,18 +1,31 @@ package storage import ( + "crypto/rand" + "encoding/csv" + "encoding/hex" "encoding/json" + "fmt" + "io" "os" "path/filepath" + "runtime" + "sort" + "strconv" + "strings" "sync" "time" ) type SessionRecord struct { + ID string `json:"id,omitempty"` Profile string `json:"profile"` StartTime string `json:"start_time"` + EndTime string `json:"end_time,omitempty"` DurationMinutes int `json:"duration_minutes"` + PlannedMinutes int `json:"planned_minutes,omitempty"` Completed bool `json:"completed"` + Status string `json:"status,omitempty"` BlockedCount int `json:"blocked_count"` } @@ -20,72 +33,437 @@ type MetricsStore struct { Sessions []SessionRecord `json:"sessions"` } +type DailyStat struct { + Date string `json:"date"` + Minutes int `json:"minutes"` + Sprints int `json:"sprints"` +} + +type AnalyticsSummary struct { + CompletedSprints int `json:"completed_sprints"` + AttemptedSprints int `json:"attempted_sprints"` + AbortedSprints int `json:"aborted_sprints"` + CompletionRate float64 `json:"completion_rate"` + TotalMinutes int `json:"total_minutes"` + TotalHours float64 `json:"total_hours"` + TotalBlocked int `json:"total_blocked"` + ActiveStreakDays int `json:"active_streak_days"` + Daily []DailyStat `json:"daily"` +} + +type ExportPayload struct { + GeneratedAt string `json:"generated_at"` + Summary AnalyticsSummary `json:"summary"` + Sessions []SessionRecord `json:"sessions"` +} + type Store struct { path string mu sync.Mutex } -func NewStore() (*Store, error) { - appData := os.Getenv("APPDATA") - var dir string - if appData != "" { - dir = filepath.Join(appData, "FocusFlow") - } else { - dir = ".focusflow" +// GetStateDir resolves the unified FocusFlow state directory shared by Go CLI and Python GUI. +// Priority: FOCUSFLOW_HOME -> %APPDATA%\FocusFlow (Windows) / ~/.config/focusflow (POSIX) -> .focusflow +func GetStateDir() string { + if override := strings.TrimSpace(os.Getenv("FOCUSFLOW_HOME")); override != "" { + return filepath.Clean(override) } + if runtime.GOOS == "windows" { + if appData := strings.TrimSpace(os.Getenv("APPDATA")); appData != "" { + return filepath.Join(appData, "FocusFlow") + } + if home, err := os.UserHomeDir(); err == nil && home != "" { + return filepath.Join(home, "AppData", "Roaming", "FocusFlow") + } + return ".focusflow" + } + if xdg := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); xdg != "" { + return filepath.Join(xdg, "focusflow") + } + if home, err := os.UserHomeDir(); err == nil && home != "" { + return filepath.Join(home, ".config", "focusflow") + } + return ".focusflow" +} +func GenerateSessionID() string { + b := make([]byte, 8) + if _, err := rand.Read(b); err != nil { + return fmt.Sprintf("ff-%d", time.Now().UnixNano()) + } + return hex.EncodeToString(b) +} + +func NewStore() (*Store, error) { + return NewStoreWithDir(GetStateDir()) +} + +func NewStoreWithDir(dir string) (*Store, error) { if err := os.MkdirAll(dir, 0755); err != nil { return nil, err } - - path := filepath.Join(dir, "sessions.json") - return &Store{path: path}, nil + return &Store{path: filepath.Join(dir, "sessions.json")}, nil } -func (s *Store) RecordSession(profile string, durationMin int, completed bool, blockedCount int) error { - s.mu.Lock() - defer s.mu.Unlock() +func (s *Store) Path() string { + return s.path +} +func (s *Store) readLocked() MetricsStore { var data MetricsStore - if raw, err := os.ReadFile(s.path); err == nil { + if raw, err := os.ReadFile(s.path); err == nil && len(raw) > 0 { _ = json.Unmarshal(raw, &data) } + if data.Sessions == nil { + data.Sessions = []SessionRecord{} + } + return data +} +func (s *Store) writeLocked(data MetricsStore) error { + if data.Sessions == nil { + data.Sessions = []SessionRecord{} + } + dir := filepath.Dir(s.path) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + out, err := json.MarshalIndent(data, "", " ") + if err != nil { + return err + } + out = append(out, '\n') + + tmpFile, err := os.CreateTemp(dir, "sessions-*.tmp") + if err != nil { + return err + } + tmpPath := tmpFile.Name() + if _, err := tmpFile.Write(out); err != nil { + _ = tmpFile.Close() + _ = os.Remove(tmpPath) + return err + } + _ = tmpFile.Sync() + if err := tmpFile.Close(); err != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Chmod(tmpPath, 0644) + if err := os.Rename(tmpPath, s.path); err != nil { + // Windows fallback if destination exists and Rename transiently fails + if writeErr := os.WriteFile(s.path, out, 0644); writeErr != nil { + _ = os.Remove(tmpPath) + return err + } + _ = os.Remove(tmpPath) + } + return nil +} + +// StartSession records the start of a focus sprint immediately so StartTime is accurate +// and unexpected crashes can mark the session as orphaned/incomplete. +func (s *Store) StartSession(sessionID, profile string, plannedMin int, startTime time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + + if sessionID == "" { + sessionID = GenerateSessionID() + } + data := s.readLocked() record := SessionRecord{ + ID: sessionID, Profile: profile, - StartTime: time.Now().Format(time.RFC3339), - DurationMinutes: durationMin, - Completed: completed, - BlockedCount: blockedCount, + StartTime: startTime.UTC().Format(time.RFC3339), + DurationMinutes: 0, + PlannedMinutes: plannedMin, + Completed: false, + Status: "running", + BlockedCount: 0, } - data.Sessions = append(data.Sessions, record) + return s.writeLocked(data) +} - out, err := json.MarshalIndent(data, "", " ") - if err != nil { - return err +// FinalizeSession updates an existing running session (or appends if missing) upon completion or abort. +func (s *Store) FinalizeSession(sessionID, profile string, durationMin int, completed bool, status string, blockedCount int, startTime, endTime time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + + if status == "" { + if completed { + status = "completed" + } else { + status = "aborted" + } + } + + data := s.readLocked() + updated := false + if sessionID != "" { + for i := len(data.Sessions) - 1; i >= 0; i-- { + if data.Sessions[i].ID == sessionID { + data.Sessions[i].DurationMinutes = durationMin + data.Sessions[i].Completed = completed + data.Sessions[i].Status = status + data.Sessions[i].BlockedCount = blockedCount + data.Sessions[i].EndTime = endTime.UTC().Format(time.RFC3339) + if data.Sessions[i].StartTime == "" && !startTime.IsZero() { + data.Sessions[i].StartTime = startTime.UTC().Format(time.RFC3339) + } + updated = true + break + } + } } - return os.WriteFile(s.path, out, 0644) + if !updated { + if startTime.IsZero() { + startTime = endTime.Add(-time.Duration(durationMin) * time.Minute) + } + data.Sessions = append(data.Sessions, SessionRecord{ + ID: sessionID, + Profile: profile, + StartTime: startTime.UTC().Format(time.RFC3339), + EndTime: endTime.UTC().Format(time.RFC3339), + DurationMinutes: durationMin, + Completed: completed, + Status: status, + BlockedCount: blockedCount, + }) + } + return s.writeLocked(data) } -func (s *Store) GetTotalStats() (int, int, int, error) { +// RecordSession records a completed or aborted session directly. +func (s *Store) RecordSession(profile string, durationMin int, completed bool, blockedCount int) error { + now := time.Now().UTC() + start := now.Add(-time.Duration(durationMin) * time.Minute) + status := "aborted" + if completed { + status = "completed" + } + return s.FinalizeSession(GenerateSessionID(), profile, durationMin, completed, status, blockedCount, start, now) +} + +// MarkOrphanedSession marks an orphaned session (by sessionID, plus any stale "running" records when sessionID matches or is empty) as completed: false. +func (s *Store) MarkOrphanedSession(sessionID string, now time.Time) (int, error) { s.mu.Lock() defer s.mu.Unlock() - var data MetricsStore - if raw, err := os.ReadFile(s.path); err == nil { - _ = json.Unmarshal(raw, &data) + data := s.readLocked() + marked := 0 + for i := range data.Sessions { + rec := &data.Sessions[i] + if (sessionID != "" && rec.ID == sessionID) || rec.Status == "running" { + if rec.Status == "running" || (sessionID != "" && rec.ID == sessionID && rec.Completed) || (sessionID != "" && rec.ID == sessionID && rec.Status == "") { + rec.Completed = false + rec.Status = "orphaned" + if rec.EndTime == "" { + rec.EndTime = now.UTC().Format(time.RFC3339) + } + marked++ + } + } + } + if marked > 0 { + if err := s.writeLocked(data); err != nil { + return 0, err + } } + return marked, nil +} + +func (s *Store) LoadSessions() ([]SessionRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + data := s.readLocked() + out := make([]SessionRecord, len(data.Sessions)) + copy(out, data.Sessions) + return out, nil +} + +func (s *Store) GetTotalStats() (int, int, int, error) { + summary, err := s.ComputeAnalytics(7, time.Now()) + if err != nil { + return 0, 0, 0, err + } + return summary.CompletedSprints, summary.TotalMinutes, summary.TotalBlocked, nil +} + +func parseSessionLocalDate(ts string, loc *time.Location) (string, bool) { + ts = strings.TrimSpace(ts) + if ts == "" { + return "", false + } + layouts := []string{ + time.RFC3339Nano, + time.RFC3339, + "2006-01-02T15:04:05", + "2006-01-02 15:04:05", + "2006-01-02", + } + for _, layout := range layouts { + if t, err := time.Parse(layout, ts); err == nil { + if layout == "2006-01-02" { + return t.Format("2006-01-02"), true + } + return t.In(loc).Format("2006-01-02"), true + } + } + if len(ts) >= 10 && ts[4] == '-' && ts[7] == '-' { + return ts[:10], true + } + return "", false +} + +// ComputeAnalytics calculates real streak, completion rate, focus hours, and N-day chart from sessions.json. +func (s *Store) ComputeAnalytics(days int, now time.Time) (*AnalyticsSummary, error) { + if days <= 0 { + days = 7 + } + sessions, err := s.LoadSessions() + if err != nil { + return nil, err + } + + loc := now.Location() + today := time.Date(now.In(loc).Year(), now.In(loc).Month(), now.In(loc).Day(), 0, 0, 0, 0, loc) + + dailyMin := make(map[string]int) + dailySprints := make(map[string]int) + completedDates := make(map[string]bool) - var totalSessions, totalMinutes, totalBlocked int - for _, rec := range data.Sessions { + var completedCount, attemptedCount, abortedCount, totalMinutes, totalBlocked int + + for _, rec := range sessions { + totalBlocked += rec.BlockedCount + if rec.Status == "running" { + continue + } + attemptedCount++ if rec.Completed { - totalSessions++ + completedCount++ totalMinutes += rec.DurationMinutes - totalBlocked += rec.BlockedCount + if dStr, ok := parseSessionLocalDate(rec.StartTime, loc); ok { + dailyMin[dStr] += rec.DurationMinutes + dailySprints[dStr]++ + if rec.DurationMinutes > 0 { + completedDates[dStr] = true + } + } + } else { + abortedCount++ + } + } + + var completionRate float64 + if attemptedCount > 0 { + completionRate = (float64(completedCount) / float64(attemptedCount)) * 100.0 + } + + // Real streak calculation: consecutive calendar days ending today or yesterday + streak := 0 + todayStr := today.Format("2006-01-02") + yesterday := today.AddDate(0, 0, -1) + yesterdayStr := yesterday.Format("2006-01-02") + + var cursor time.Time + hasStart := false + if completedDates[todayStr] { + cursor = today + hasStart = true + } else if completedDates[yesterdayStr] { + cursor = yesterday + hasStart = true + } + if hasStart { + for completedDates[cursor.Format("2006-01-02")] { + streak++ + cursor = cursor.AddDate(0, 0, -1) } } - return totalSessions, totalMinutes, totalBlocked, nil + daily := make([]DailyStat, 0, days) + for i := days - 1; i >= 0; i-- { + d := today.AddDate(0, 0, -i).Format("2006-01-02") + daily = append(daily, DailyStat{ + Date: d, + Minutes: dailyMin[d], + Sprints: dailySprints[d], + }) + } + + return &AnalyticsSummary{ + CompletedSprints: completedCount, + AttemptedSprints: attemptedCount, + AbortedSprints: abortedCount, + CompletionRate: completionRate, + TotalMinutes: totalMinutes, + TotalHours: float64(totalMinutes) / 60.0, + TotalBlocked: totalBlocked, + ActiveStreakDays: streak, + Daily: daily, + }, nil +} + +func (s *Store) ExportJSON(w io.Writer, days int, now time.Time) error { + sessions, err := s.LoadSessions() + if err != nil { + return err + } + summary, err := s.ComputeAnalytics(days, now) + if err != nil { + return err + } + payload := ExportPayload{ + GeneratedAt: now.UTC().Format(time.RFC3339), + Summary: *summary, + Sessions: sessions, + } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(payload) +} + +func (s *Store) ExportCSV(w io.Writer) error { + sessions, err := s.LoadSessions() + if err != nil { + return err + } + sort.SliceStable(sessions, func(i, j int) bool { + return sessions[i].StartTime < sessions[j].StartTime + }) + + cw := csv.NewWriter(w) + header := []string{"id", "profile", "start_time", "end_time", "duration_minutes", "planned_minutes", "completed", "status", "blocked_count"} + if err := cw.Write(header); err != nil { + return err + } + for _, rec := range sessions { + status := rec.Status + if status == "" { + if rec.Completed { + status = "completed" + } else { + status = "aborted" + } + } + row := []string{ + rec.ID, + rec.Profile, + rec.StartTime, + rec.EndTime, + strconv.Itoa(rec.DurationMinutes), + strconv.Itoa(rec.PlannedMinutes), + strconv.FormatBool(rec.Completed), + status, + strconv.Itoa(rec.BlockedCount), + } + if err := cw.Write(row); err != nil { + return err + } + } + cw.Flush() + return cw.Error() } diff --git a/pkg/storage/store_test.go b/pkg/storage/store_test.go new file mode 100644 index 0000000..cbd0cec --- /dev/null +++ b/pkg/storage/store_test.go @@ -0,0 +1,92 @@ +package storage + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + "time" +) + +func TestStore_LifecycleStreakAnalyticsAndExport(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("FOCUSFLOW_HOME", tmpDir) + + store, err := NewStore() + if err != nil { + t.Fatalf("NewStore failed: %v", err) + } + + // Empty store has 0 streak, 0 hours, 0% completion (zero fake data) + emptySummary, err := store.ComputeAnalytics(7, time.Now()) + if err != nil { + t.Fatalf("ComputeAnalytics empty: %v", err) + } + if emptySummary.ActiveStreakDays != 0 || emptySummary.TotalMinutes != 0 || emptySummary.CompletionRate != 0 { + t.Fatalf("expected all-zero initial analytics, got %+v", emptySummary) + } + + now := time.Date(2026, 11, 10, 15, 0, 0, 0, time.UTC) + day2 := now.AddDate(0, 0, -2) + day1 := now.AddDate(0, 0, -1) + + // 3 consecutive completed days + 1 aborted session + 1 running session that gets orphaned + _ = store.FinalizeSession("s1", "study", 30, true, "completed", 2, day2, day2.Add(30*time.Minute)) + _ = store.FinalizeSession("s2", "dev", 60, true, "completed", 4, day1, day1.Add(60*time.Minute)) + _ = store.StartSession("s3", "study", 30, now.Add(-45*time.Minute)) + _ = store.FinalizeSession("s3", "study", 30, true, "completed", 1, now.Add(-45*time.Minute), now.Add(-15*time.Minute)) + _ = store.FinalizeSession("s4", "hardcore", 10, false, "aborted", 3, now.Add(-12*time.Minute), now.Add(-2*time.Minute)) + + // Orphan session lifecycle + _ = store.StartSession("orphan-99", "dev", 50, now.Add(-5*time.Minute)) + marked, err := store.MarkOrphanedSession("orphan-99", now) + if err != nil || marked != 1 { + t.Fatalf("expected 1 orphaned session marked, got marked=%d err=%v", marked, err) + } + + summary, err := store.ComputeAnalytics(7, now) + if err != nil { + t.Fatalf("ComputeAnalytics failed: %v", err) + } + if summary.CompletedSprints != 3 { + t.Errorf("CompletedSprints = %d, want 3", summary.CompletedSprints) + } + if summary.AttemptedSprints != 5 || summary.AbortedSprints != 2 { + t.Errorf("Attempted=%d Aborted=%d, want 5 and 2", summary.AttemptedSprints, summary.AbortedSprints) + } + if summary.TotalMinutes != 120 || summary.TotalHours != 2.0 { + t.Errorf("TotalMinutes=%d TotalHours=%.1f, want 120 and 2.0", summary.TotalMinutes, summary.TotalHours) + } + if summary.ActiveStreakDays != 3 { + t.Errorf("ActiveStreakDays = %d, want 3", summary.ActiveStreakDays) + } + if summary.TotalBlocked != 10 { + t.Errorf("TotalBlocked = %d, want 10", summary.TotalBlocked) + } + if len(summary.Daily) != 7 { + t.Errorf("len(Daily) = %d, want 7", len(summary.Daily)) + } + + // JSON export + var jsonBuf bytes.Buffer + if err := store.ExportJSON(&jsonBuf, 7, now); err != nil { + t.Fatalf("ExportJSON: %v", err) + } + var payload ExportPayload + if err := json.Unmarshal(jsonBuf.Bytes(), &payload); err != nil { + t.Fatalf("unmarshal export JSON: %v", err) + } + if len(payload.Sessions) != 5 || payload.Summary.ActiveStreakDays != 3 { + t.Errorf("unexpected exported JSON payload: %+v", payload.Summary) + } + + // CSV export + var csvBuf bytes.Buffer + if err := store.ExportCSV(&csvBuf); err != nil { + t.Fatalf("ExportCSV: %v", err) + } + csvStr := csvBuf.String() + if !strings.Contains(csvStr, "id,profile,start_time,end_time,duration_minutes") || !strings.Contains(csvStr, "orphan-99") { + t.Errorf("unexpected CSV output:\n%s", csvStr) + } +} diff --git a/pkg/tui/hud.go b/pkg/tui/hud.go index b6cb394..b21fedb 100644 --- a/pkg/tui/hud.go +++ b/pkg/tui/hud.go @@ -2,28 +2,50 @@ package tui import ( "fmt" + "io" + "os" "strings" + + "github.com/aloneangel45/focusflow/pkg/storage" ) -func PrintBanner() { +const DefaultVersion = "2.1.0" + +func FormatBanner(version string) string { + if strings.TrimSpace(version) == "" { + version = DefaultVersion + } banner := ` ███████╗ ██████╗ ██████╗██╗ ██╗███████╗███████╗██╗ ██████╗ ██╗ ██╗ ██╔════╝██╔═══██╗██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔═══██╗██║ ██║ █████╗ ██║ ██║██║ ██║ ██║███████╗█████╗ ██║ ██║ ██║██║ █╗ ██║ ██╔══╝ ██║ ██║██║ ██║ ██║╚════██║██╔══╝ ██║ ██║ ██║██║███╗██║ ██║ ╚██████╔╝╚██████╗╚██████╔╝███████║██║ ███████╗╚██████╔╝╚███╔███╔╝ - ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝ -` - fmt.Println(banner) - fmt.Println(" 🛡️ Kernel-Level Deep Work & Distraction Shield v2.0.0") - fmt.Println(" " + strings.Repeat("─", 68) + "\n") + ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝` + return fmt.Sprintf("%s\n\n [FOCUSFLOW] Native Deep Work & Distraction Shield v%s\n %s\n\n", + banner, version, strings.Repeat("─", 72)) } -func RenderProgress(elapsedSeconds, totalSeconds int, profileName string, blockedCount int) { +func PrintBanner() { + PrintBannerTo(os.Stdout, DefaultVersion) +} + +func PrintBannerWithVersion(version string) { + PrintBannerTo(os.Stdout, version) +} + +func PrintBannerTo(w io.Writer, version string) { + _, _ = fmt.Fprint(w, FormatBanner(version)) +} + +func FormatProgress(elapsedSeconds, totalSeconds int, profileName string, blockedCount int) string { percent := 0 if totalSeconds > 0 { percent = (elapsedSeconds * 100) / totalSeconds } + if percent < 0 { + percent = 0 + } if percent > 100 { percent = 100 } @@ -37,6 +59,38 @@ func RenderProgress(elapsedSeconds, totalSeconds int, profileName string, blocke totalMin := totalSeconds / 60 totalSec := totalSeconds % 60 - fmt.Printf("\r [%02d:%02d/%02d:%02d] [%s] %3d%% | Profile: %-8s | Blocked Distractions: %d ", + return fmt.Sprintf("\r [%02d:%02d/%02d:%02d] [%s] %3d%% | Profile: %-8s | Blocked: %d ", elapsedMin, elapsedSec, totalMin, totalSec, bar, percent, profileName, blockedCount) } + +func RenderProgress(elapsedSeconds, totalSeconds int, profileName string, blockedCount int) { + _, _ = fmt.Fprint(os.Stdout, FormatProgress(elapsedSeconds, totalSeconds, profileName, blockedCount)) +} + +// FormatDailyChart renders a clean ASCII bar chart for focus minutes across N days. +func FormatDailyChart(daily []storage.DailyStat) string { + if len(daily) == 0 { + return " (No daily history available)\n" + } + maxMin := 0 + for _, d := range daily { + if d.Minutes > maxMin { + maxMin = d.Minutes + } + } + + const maxWidth = 28 + var b strings.Builder + for _, d := range daily { + filled := 0 + if maxMin > 0 && d.Minutes > 0 { + filled = (d.Minutes * maxWidth) / maxMin + if filled == 0 { + filled = 1 + } + } + bar := strings.Repeat("█", filled) + strings.Repeat("░", maxWidth-filled) + b.WriteString(fmt.Sprintf(" %s | %s | %4d min (%d sprints)\n", d.Date, bar, d.Minutes, d.Sprints)) + } + return b.String() +} diff --git a/pkg/tui/hud_test.go b/pkg/tui/hud_test.go new file mode 100644 index 0000000..8ed7521 --- /dev/null +++ b/pkg/tui/hud_test.go @@ -0,0 +1,40 @@ +package tui + +import ( + "strings" + "testing" + + "github.com/aloneangel45/focusflow/pkg/storage" +) + +func containsEmoji(s string) bool { + for _, r := range s { + if (r >= 0x1F000 && r <= 0x1FAFF) || (r >= 0x2600 && r <= 0x27BF) || r == 0xFE0F { + return true + } + } + return false +} + +func TestHUD_BannerProgressAndDailyChart_ZeroEmojis(t *testing.T) { + banner := FormatBanner("2.1.0") + if !strings.Contains(banner, "v2.1.0") { + t.Errorf("expected version in banner") + } + if containsEmoji(banner) { + t.Errorf("banner contains forbidden emoji/dingbat characters:\n%s", banner) + } + + prog := FormatProgress(300, 600, "dev", 4) + if !strings.Contains(prog, "50%") || !strings.Contains(prog, "05:00/10:00") || containsEmoji(prog) { + t.Errorf("unexpected progress string: %q", prog) + } + + chart := FormatDailyChart([]storage.DailyStat{ + {Date: "2026-11-09", Minutes: 0, Sprints: 0}, + {Date: "2026-11-10", Minutes: 50, Sprints: 1}, + }) + if !strings.Contains(chart, "2026-11-10") || !strings.Contains(chart, "50 min") || containsEmoji(chart) { + t.Errorf("unexpected chart output:\n%s", chart) + } +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..34968d1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools>=68.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "focusflow" +version = "2.1.0" +description = "Crash-safe deep work discipline engine, dual-stack atomic hosts blocker, Win32 process supervisor, and Catppuccin Mocha desktop HUD." +readme = "README.md" +requires-python = ">=3.10" +license = { text = "MIT" } +authors = [ + { name = "aloneangel45" } +] +dependencies = [] + +[project.optional-dependencies] +reports = ["Pillow>=10.0.0"] +proc = ["psutil>=5.9.0"] +dev = ["pytest>=8.0.0"] + +[project.scripts] +focusflow-gui = "FocusFlowGUI:main" + +[tool.setuptools.packages.find] +include = ["focusflow_core*"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-q" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bd1f155 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +# FocusFlow v2.1.0 — Python Runtime Dependencies +# +# Required runtime dependencies: NONE (0 external packages required). +# On Windows 10/11, FocusFlowGUI and focusflow_core operate natively on the Python +# standard library (tkinter, ctypes Win32 Toolhelp32 / ReplaceFileW / ShellExecuteW, +# hashlib, json, csv, threading). +# +# Optional extras (uncomment or install via `pip install .[reports,dev]`): +# Pillow>=10.0.0 # Optional: export visual PNG analytics cards from the desktop HUD +# psutil>=5.9.0 # Optional: cross-platform process enumeration fallback +# pytest>=8.0.0 # Development: run the automated Python test suite (`python -m pytest -v`) diff --git a/src/engine/anti_cheat.rs b/src/engine/anti_cheat.rs deleted file mode 100644 index 3a9d7a1..0000000 --- a/src/engine/anti_cheat.rs +++ /dev/null @@ -1,40 +0,0 @@ -use crate::engine::process::ProcessSupervisor; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StrictnessLevel { - Relaxed, // Only blocks websites and games, allows Task Manager - Standard, // Blocks websites, distraction apps, logs attempts - Hardcore, // Actively suppresses Task Manager and terminal escapes during active sprint -} - -pub struct AntiCheatGuard { - level: StrictnessLevel, - supervisor: ProcessSupervisor, -} - -impl AntiCheatGuard { - pub fn new(level: StrictnessLevel) -> Self { - let blocked = match level { - StrictnessLevel::Hardcore => vec![ - "taskmgr.exe".to_string(), - "processhacker.exe".to_string(), - "procmon.exe".to_string(), - "procexp.exe".to_string(), - ], - StrictnessLevel::Standard | StrictnessLevel::Relaxed => Vec::new(), - }; - - Self { - level, - supervisor: ProcessSupervisor::new(&blocked), - } - } - - pub fn enforce(&self) -> Vec { - if self.level == StrictnessLevel::Hardcore { - self.supervisor.scan_and_terminate() - } else { - Vec::new() - } - } -} diff --git a/src/engine/dns.rs b/src/engine/dns.rs deleted file mode 100644 index fb29e68..0000000 --- a/src/engine/dns.rs +++ /dev/null @@ -1,36 +0,0 @@ -use std::process::Command; -use std::io; - -pub struct DnsEngine; - -impl DnsEngine { - /// Flushes Windows resolver cache so hosts edits take effect immediately across all sockets and browsers. - pub fn flush_resolver_cache() -> io::Result<()> { - let output = Command::new("ipconfig") - .arg("/flushdns") - .output()?; - - if output.status.success() { - Ok(()) - } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to flush DNS: {}", String::from_utf8_lossy(&output.stderr)), - )) - } - } - - /// Common DNS-over-HTTPS (DoH) endpoints that can bypass hosts file if left open in Chrome/Brave/Edge. - pub fn get_doh_bypass_domains() -> Vec { - vec![ - "cloudflare-dns.com".to_string(), - "one.one.one.one".to_string(), - "dns.google".to_string(), - "dns.google.com".to_string(), - "dns.quad9.net".to_string(), - "doh.opendns.com".to_string(), - "chrome.cloudflare-dns.com".to_string(), - "mozilla.cloudflare-dns.com".to_string(), - ] - } -} diff --git a/src/engine/hosts.rs b/src/engine/hosts.rs deleted file mode 100644 index 4691738..0000000 --- a/src/engine/hosts.rs +++ /dev/null @@ -1,153 +0,0 @@ -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; -use std::path::{Path, PathBuf}; -use sha2::{Digest, Sha256}; - -pub const HOSTS_PATH: &str = r"C:\Windows\System32\drivers\etc\hosts"; -pub const BACKUP_SUFFIX: &str = ".focusflow.bak"; -pub const MARKER_BEGIN: &str = "# --- BEGIN FOCUSFLOW MANAGED BLOCK ---"; -pub const MARKER_END: &str = "# --- END FOCUSFLOW MANAGED BLOCK ---"; - -#[derive(Debug)] -pub struct HostsManager { - hosts_path: PathBuf, - backup_path: PathBuf, -} - -impl HostsManager { - pub fn new() -> Self { - Self::with_path(PathBuf::from(HOSTS_PATH)) - } - - pub fn with_path(hosts_path: PathBuf) -> Self { - let mut backup_path = hosts_path.clone(); - backup_path.set_extension("focusflow.bak"); - Self { - hosts_path, - backup_path, - } - } - - pub fn compute_sha256(path: &Path) -> io::Result { - let mut file = File::open(path)?; - let mut hasher = Sha256::new(); - let mut buffer = [0u8; 8192]; - loop { - let bytes_read = file.read(&mut buffer)?; - if bytes_read == 0 { - break; - } - hasher.update(&buffer[..bytes_read]); - } - Ok(format!("{:x}", hasher.finalize())) - } - - pub fn backup(&self) -> io::Result { - if !self.hosts_path.exists() { - return Err(io::Error::new( - io::ErrorKind::NotFound, - format!("Hosts file not found at {:?}", self.hosts_path), - )); - } - - fs::copy(&self.hosts_path, &self.backup_path)?; - Self::compute_sha256(&self.backup_path) - } - - pub fn apply_blocklist(&self, domains: &[String]) -> io::Result<()> { - if domains.is_empty() { - return Ok(()); - } - - // Ensure backup exists first - if !self.backup_path.exists() { - self.backup()?; - } - - let content = fs::read_to_string(&self.hosts_path)?; - let clean_content = self.strip_managed_block(&content); - - let mut block_entries = String::new(); - block_entries.push_str("\n"); - block_entries.push_str(MARKER_BEGIN); - block_entries.push_str("\n"); - block_entries.push_str("# FocusFlow V2 - Distraction-free system guard\n"); - - for domain in domains { - let trimmed = domain.trim().to_lowercase(); - if !trimmed.is_empty() && !trimmed.starts_with('#') { - block_entries.push_str(&format!("0.0.0.0 {}\n", trimmed)); - if !trimmed.starts_with("www.") { - block_entries.push_str(&format!("0.0.0.0 www.{}\n", trimmed)); - } - } - } - - block_entries.push_str(MARKER_END); - block_entries.push_str("\n"); - - let new_content = format!("{}{}", clean_content.trim_end(), block_entries); - - // Atomic file write using temporary file in same folder - let temp_path = self.hosts_path.with_extension("tmp"); - { - let mut temp_file = OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .open(&temp_path)?; - temp_file.write_all(new_content.as_bytes())?; - temp_file.flush()?; - } - - fs::rename(&temp_path, &self.hosts_path)?; - Ok(()) - } - - pub fn rollback(&self) -> io::Result<()> { - if self.backup_path.exists() { - fs::copy(&self.backup_path, &self.hosts_path)?; - let _ = fs::remove_file(&self.backup_path); - return Ok(()); - } - - // Fallback: Strip managed block directly - if self.hosts_path.exists() { - let content = fs::read_to_string(&self.hosts_path)?; - let clean_content = self.strip_managed_block(&content); - fs::write(&self.hosts_path, clean_content)?; - } - - Ok(()) - } - - fn strip_managed_block(&self, content: &str) -> String { - let mut result = String::new(); - let mut inside_block = false; - - for line in content.lines() { - if line.contains(MARKER_BEGIN) { - inside_block = true; - continue; - } - if line.contains(MARKER_END) { - inside_block = false; - continue; - } - if !inside_block { - result.push_str(line); - result.push('\n'); - } - } - - result - } - - pub fn is_active(&self) -> bool { - if let Ok(content) = fs::read_to_string(&self.hosts_path) { - content.contains(MARKER_BEGIN) - } else { - false - } - } -} diff --git a/src/engine/mod.rs b/src/engine/mod.rs deleted file mode 100644 index e7e8215..0000000 --- a/src/engine/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod hosts; -pub mod process; -pub mod dns; -pub mod anti_cheat; - -pub use hosts::HostsManager; -pub use process::ProcessSupervisor; -pub use dns::DnsEngine; -pub use anti_cheat::{AntiCheatGuard, StrictnessLevel}; diff --git a/src/engine/process.rs b/src/engine/process.rs deleted file mode 100644 index 4bc0a63..0000000 --- a/src/engine/process.rs +++ /dev/null @@ -1,76 +0,0 @@ -use std::collections::HashSet; -use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; -use windows_sys::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS, -}; -use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; - -pub struct ProcessSupervisor { - blocked_process_names: HashSet, -} - -impl ProcessSupervisor { - pub fn new(blocked: &[String]) -> Self { - let mut set = HashSet::new(); - for b in blocked { - set.insert(b.trim().to_lowercase()); - } - Self { - blocked_process_names: set, - } - } - - pub fn scan_and_terminate(&self) -> Vec { - let mut terminated = Vec::new(); - if self.blocked_process_names.is_empty() { - return terminated; - } - - unsafe { - let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - if snapshot == INVALID_HANDLE_VALUE { - return terminated; - } - - let mut entry: PROCESSENTRY32 = std::mem::zeroed(); - entry.dwSize = std::mem::size_of::() as u32; - - if Process32First(snapshot, &mut entry) != 0 { - loop { - // Extract process name from CHAR array - let exe_name = Self::parse_exe_name(&entry.szExeFile); - let exe_lower = exe_name.to_lowercase(); - - if self.blocked_process_names.contains(&exe_lower) { - let h_proc = OpenProcess(PROCESS_TERMINATE, 0, entry.th32ProcessID); - if !h_proc.is_null() && h_proc != INVALID_HANDLE_VALUE { - if TerminateProcess(h_proc, 1) != 0 { - terminated.push(format!("{} (PID: {})", exe_name, entry.th32ProcessID)); - } - CloseHandle(h_proc); - } - } - - if Process32Next(snapshot, &mut entry) == 0 { - break; - } - } - } - - CloseHandle(snapshot); - } - - terminated - } - - fn parse_exe_name(raw: &[i8]) -> String { - let mut bytes = Vec::new(); - for &b in raw { - if b == 0 { - break; - } - bytes.push(b as u8); - } - String::from_utf8_lossy(&bytes).to_string() - } -} diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index 227f074..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod engine; -pub mod profile; -pub mod storage; -pub mod tui; - -pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 1d9f263..0000000 --- a/src/main.rs +++ /dev/null @@ -1,206 +0,0 @@ -use clap::{Parser, Subcommand}; -use colored::*; -use focusflow::engine::{AntiCheatGuard, DnsEngine, HostsManager, ProcessSupervisor, StrictnessLevel}; -use focusflow::profile::FocusProfile; -use focusflow::storage::Database; -use focusflow::tui::TerminalHud; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::thread; -use std::time::Duration; - -#[derive(Parser)] -#[command( - name = "focusflow", - version = focusflow::VERSION, - about = "⚡ Kernel-Level Deep Work Discipline Engine & Atomic Hosts Blocker in Rust", - long_about = "FocusFlow V2 enforces unyielding digital discipline through low-overhead Win32 process supervision, atomic hosts-file management, and automatic DNS-over-HTTPS bypass mitigation." -)] -struct Cli { - #[command(subcommand)] - command: Commands, -} - -#[derive(Subcommand)] -enum Commands { - /// Start a deep work session with atomic blocking active - Start { - /// Profile to activate (dev, study, hardcore) - #[arg(short, long, default_value = "study")] - profile: String, - - /// Session duration in minutes (overrides profile default) - #[arg(short, long)] - minutes: Option, - - /// Anti-cheat strictness level (relaxed, standard, hardcore) - #[arg(short, long, default_value = "standard")] - strictness: String, - }, - - /// Rollback hosts file immediately and restore unrestricted system access - Stop, - - /// Check whether FocusFlow active blocklist is currently engaged - Status, - - /// Flush system DNS resolver cache immediately - Flush, - - /// Display historical focus session metrics and streak summary - Stats, -} - -fn main() -> Result<(), Box> { - let cli = Cli::parse(); - TerminalHud::print_banner(); - - match cli.command { - Commands::Start { - profile, - minutes, - strictness, - } => { - let prof = FocusProfile::load_or_default(&profile); - let duration_min = minutes.unwrap_or(prof.default_work_minutes); - let total_seconds = (duration_min as u64) * 60; - - let strict_level = match strictness.to_lowercase().as_str() { - "hardcore" => StrictnessLevel::Hardcore, - "relaxed" => StrictnessLevel::Relaxed, - _ => StrictnessLevel::Standard, - }; - - println!( - " {} Starting {} session ({} minutes | Strictness: {:?})", - "▶".bright_green().bold(), - prof.name.bright_yellow().bold(), - duration_min.to_string().bright_cyan().bold(), - strict_level - ); - - let hosts = Arc::new(HostsManager::new()); - let dns = DnsEngine; - let process_sup = ProcessSupervisor::new(&prof.blocked_processes); - let anti_cheat = AntiCheatGuard::new(strict_level); - - // Step 1: Engage Hosts Blocklist - print!(" {} Engaging atomic hosts blocklist... ", "•".bright_blue()); - let mut all_domains = prof.blocked_domains.clone(); - all_domains.extend(DnsEngine::get_doh_bypass_domains()); - - match hosts.apply_blocklist(&all_domains) { - Ok(_) => println!("{}", "OK (Backup secured with SHA-256)".bright_green()), - Err(e) => { - println!("{}", format!("FAILED ({})", e).bright_red()); - println!(" {} Please run terminal as Administrator to modify system hosts.", "⚠".bright_yellow()); - } - } - - // Step 2: Flush DNS resolver cache - print!(" {} Purging DNS resolver cache (Anti-DoH)... ", "•".bright_blue()); - let _ = DnsEngine::flush_resolver_cache(); - println!("{}", "OK".bright_green()); - - // Setup graceful Ctrl+C interrupt handler - let running = Arc::new(AtomicBool::new(true)); - let r_clone = running.clone(); - let h_clone = hosts.clone(); - - ctrlc::set_handler(move || { - println!("\n {} Interrupt signal received! Rolling back hosts...", "⚠".bright_yellow()); - let _ = h_clone.rollback(); - let _ = DnsEngine::flush_resolver_cache(); - r_clone.store(false, Ordering::SeqCst); - println!(" {} System access cleanly restored. Exiting.", "✔".bright_green()); - std::process::exit(0); - }) - .expect("Error setting Ctrl-C handler"); - - // Step 3: Run interactive TUI loop - let hud = TerminalHud::new_sprint(total_seconds, &prof.name); - let mut elapsed: u64 = 0; - let mut total_blocked: u32 = 0; - - while running.load(Ordering::SeqCst) && elapsed < total_seconds { - thread::sleep(Duration::from_secs(1)); - elapsed += 1; - - // Process surveillance scan - let terminated_procs = process_sup.scan_and_terminate(); - let anti_cheat_procs = anti_cheat.enforce(); - - let scan_hits = (terminated_procs.len() + anti_cheat_procs.len()) as u32; - if scan_hits > 0 { - total_blocked += scan_hits; - for p in terminated_procs.iter().chain(anti_cheat_procs.iter()) { - println!("\n {} Terminated distraction: {}", "✘".bright_red().bold(), p.bright_white()); - } - } - - hud.update(elapsed, total_blocked); - } - - hud.finish(); - - // Session completed cleanly - let _ = hosts.rollback(); - let _ = DnsEngine::flush_resolver_cache(); - - // Record into SQLite Database - if let Ok(db) = Database::open() { - let _ = db.record_session(&prof.name, duration_min, true, total_blocked); - } - - println!("\n {} Great job! All system protections rolled back.", "✔".bright_green().bold()); - } - - Commands::Stop => { - println!(" {} Rolling back hosts file and flushing DNS...", "•".bright_blue()); - let hosts = HostsManager::new(); - match hosts.rollback() { - Ok(_) => { - let _ = DnsEngine::flush_resolver_cache(); - println!(" {} Clean rollback complete. Unrestricted access restored.", "✔".bright_green()); - } - Err(e) => { - println!(" {} Rollback failed: {}", "✘".bright_red(), e); - } - } - } - - Commands::Status => { - let hosts = HostsManager::new(); - if hosts.is_active() { - println!(" {} FocusFlow guard is currently {}.", "•".bright_white(), "ACTIVE (Lockdown Engaged)".bright_red().bold()); - } else { - println!(" {} FocusFlow guard is {}.", "•".bright_white(), "INACTIVE (Unrestricted)".bright_green().bold()); - } - } - - Commands::Flush => { - print!(" {} Purging DNS resolver cache... ", "•".bright_blue()); - match DnsEngine::flush_resolver_cache() { - Ok(_) => println!("{}", "OK".bright_green()), - Err(e) => println!("{}", format!("FAILED ({})", e).bright_red()), - } - } - - Commands::Stats => { - println!(" {} FocusFlow Historical Metrics:\n", "📊".bright_cyan()); - match Database::open() { - Ok(db) => { - if let Ok((sessions, minutes, blocked)) = db.get_total_stats() { - let hours = (minutes as f64) / 60.0; - println!(" • Total Completed Sprints: {}", sessions.to_string().bright_yellow().bold()); - println!(" • Total Deep Work Hours: {:.1} hrs", hours); - println!(" • Distractions Blocked: {}", blocked.to_string().bright_red().bold()); - } - } - Err(e) => println!(" {} Could not read metrics database: {}", "✘".bright_red(), e), - } - } - } - - Ok(()) -} diff --git a/src/profile/mod.rs b/src/profile/mod.rs deleted file mode 100644 index 9eb56ad..0000000 --- a/src/profile/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod models; -pub use models::FocusProfile; diff --git a/src/profile/models.rs b/src/profile/models.rs deleted file mode 100644 index cae0811..0000000 --- a/src/profile/models.rs +++ /dev/null @@ -1,85 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FocusProfile { - pub name: String, - pub description: String, - pub blocked_domains: Vec, - pub blocked_processes: Vec, - pub default_work_minutes: u32, - pub default_break_minutes: u32, -} - -impl FocusProfile { - pub fn dev_profile() -> Self { - Self { - name: "dev".to_string(), - description: "Developer Deep Work (Keeps GitHub & Docs open; blocks social & gaming)".to_string(), - blocked_domains: vec![ - "twitter.com".to_string(), - "x.com".to_string(), - "instagram.com".to_string(), - "tiktok.com".to_string(), - "reddit.com".to_string(), - "facebook.com".to_string(), - "netflix.com".to_string(), - "twitch.tv".to_string(), - ], - blocked_processes: vec![ - "discord.exe".to_string(), - "spotify.exe".to_string(), - "steam.exe".to_string(), - "epicgameslauncher.exe".to_string(), - "riotclientservices.exe".to_string(), - ], - default_work_minutes: 50, - default_break_minutes: 10, - } - } - - pub fn study_profile() -> Self { - Self { - name: "study".to_string(), - description: "Academic & Exam Preparation Mode (YKS/KPSS/LGS - Zero entertainment)".to_string(), - blocked_domains: vec![ - "youtube.com".to_string(), - "instagram.com".to_string(), - "tiktok.com".to_string(), - "twitter.com".to_string(), - "x.com".to_string(), - "twitch.tv".to_string(), - "kick.com".to_string(), - "netflix.com".to_string(), - "disneyplus.com".to_string(), - "reddit.com".to_string(), - ], - blocked_processes: vec![ - "steam.exe".to_string(), - "discord.exe".to_string(), - "spotify.exe".to_string(), - "telegram.exe".to_string(), - "whatsapp.exe".to_string(), - "riotclientservices.exe".to_string(), - "leagueclient.exe".to_string(), - "valorant.exe".to_string(), - ], - default_work_minutes: 25, - default_break_minutes: 5, - } - } - - pub fn hardcore_profile() -> Self { - let mut p = Self::study_profile(); - p.name = "hardcore".to_string(); - p.description = "Aegis Lockdown - Maximum discipline with Anti-Cheat guardrails".to_string(); - p - } - - pub fn load_or_default(profile_name: &str) -> Self { - match profile_name.to_lowercase().as_str() { - "dev" | "coding" => Self::dev_profile(), - "hardcore" | "lockdown" => Self::hardcore_profile(), - _ => Self::study_profile(), - } - } -} diff --git a/src/storage/db.rs b/src/storage/db.rs deleted file mode 100644 index 60c3a26..0000000 --- a/src/storage/db.rs +++ /dev/null @@ -1,124 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::fs::{self, File}; -use std::io::{self, BufReader, BufWriter}; -use std::path::PathBuf; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SessionRecord { - pub profile: String, - pub start_time: String, - pub duration_minutes: u32, - pub completed: bool, - pub blocked_count: u32, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct MetricsStore { - pub sessions: Vec, -} - -pub struct Database { - db_path: Option, - in_memory: Option>, -} - -impl Database { - pub fn open() -> io::Result { - let db_dir = Self::get_db_dir(); - fs::create_dir_all(&db_dir)?; - let db_path = db_dir.join("sessions.json"); - - if !db_path.exists() { - let initial = MetricsStore::default(); - let writer = BufWriter::new(File::create(&db_path)?); - serde_json::to_writer_pretty(writer, &initial)?; - } - - Ok(Self { - db_path: Some(db_path), - in_memory: None, - }) - } - - pub fn open_in_memory() -> io::Result { - Ok(Self { - db_path: None, - in_memory: Some(std::sync::Mutex::new(MetricsStore::default())), - }) - } - - fn get_db_dir() -> PathBuf { - if let Some(app_data) = std::env::var_os("APPDATA") { - PathBuf::from(app_data).join("FocusFlow") - } else { - PathBuf::from(".focusflow") - } - } - - fn load(&self) -> io::Result { - if let Some(ref mem) = self.in_memory { - let guard = mem.lock().unwrap(); - return Ok(guard.clone()); - } - - let path = self.db_path.as_ref().unwrap(); - if !path.exists() { - return Ok(MetricsStore::default()); - } - - let reader = BufReader::new(File::open(path)?); - let store = serde_json::from_reader(reader).unwrap_or_default(); - Ok(store) - } - - fn save(&self, store: &MetricsStore) -> io::Result<()> { - if let Some(ref mem) = self.in_memory { - let mut guard = mem.lock().unwrap(); - *guard = store.clone(); - return Ok(()); - } - - let path = self.db_path.as_ref().unwrap(); - let writer = BufWriter::new(File::create(path)?); - serde_json::to_writer_pretty(writer, store)?; - Ok(()) - } - - pub fn record_session( - &self, - profile: &str, - duration_minutes: u32, - completed: bool, - blocked_count: u32, - ) -> io::Result<()> { - let mut store = self.load()?; - let start_time = chrono::Local::now().to_rfc3339(); - - store.sessions.push(SessionRecord { - profile: profile.to_string(), - start_time, - duration_minutes, - completed, - blocked_count, - }); - - self.save(&store) - } - - pub fn get_total_stats(&self) -> io::Result<(u32, u32, u32)> { - let store = self.load()?; - let mut total_sessions: u32 = 0; - let mut total_minutes: u32 = 0; - let mut total_blocked: u32 = 0; - - for s in &store.sessions { - if s.completed { - total_sessions += 1; - total_minutes += s.duration_minutes; - total_blocked += s.blocked_count; - } - } - - Ok((total_sessions, total_minutes, total_blocked)) - } -} diff --git a/src/storage/mod.rs b/src/storage/mod.rs deleted file mode 100644 index 4ce25ce..0000000 --- a/src/storage/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod db; -pub use db::{Database, SessionRecord}; diff --git a/src/tui/display.rs b/src/tui/display.rs deleted file mode 100644 index 9e03bde..0000000 --- a/src/tui/display.rs +++ /dev/null @@ -1,50 +0,0 @@ -use colored::*; -use indicatif::{ProgressBar, ProgressStyle}; -use std::time::Duration; - -pub struct TerminalHud { - progress_bar: ProgressBar, -} - -impl TerminalHud { - pub fn print_banner() { - println!("{}", r" - ███████╗ ██████╗ ██████╗██╗ ██╗███████╗███████╗██╗ ██████╗ ██╗ ██╗ - ██╔════╝██╔═══██╗██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔═══██╗██║ ██║ - █████╗ ██║ ██║██║ ██║ ██║███████╗█████╗ ██║ ██║ ██║██║ █╗ ██║ - ██╔══╝ ██║ ██║██║ ██║ ██║╚════██║██╔══╝ ██║ ██║ ██║██║███╗██║ - ██║ ╚██████╔╝╚██████╗╚██████╔╝███████║██║ ███████╗╚██████╔╝╚███╔███╔╝ - ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝ - ".bright_cyan().bold()); - println!( - " {} {}", - "🛡️ Kernel-Level Deep Work & Distraction Shield".bright_white().bold(), - "v2.0.0 (Rust Edition)".bright_green() - ); - println!(" {}\n", "──────────────────────────────────────────────────────────────────────".dimmed()); - } - - pub fn new_sprint(total_seconds: u64, profile_name: &str) -> Self { - let pb = ProgressBar::new(total_seconds); - pb.set_style( - ProgressStyle::default_bar() - .template(" [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len}s ({percent}%) | {msg}") - .unwrap() - .progress_chars("█▓▒░ "), - ); - pb.set_message(format!("Profile: {} | Active Guard", profile_name.bright_yellow())); - Self { progress_bar: pb } - } - - pub fn update(&self, elapsed: u64, blocked_count: u32) { - self.progress_bar.set_position(elapsed); - self.progress_bar.set_message(format!( - "Blocked Distractions: {}", - blocked_count.to_string().bright_red().bold() - )); - } - - pub fn finish(&self) { - self.progress_bar.finish_with_message("Sprint Complete! Take a well-deserved break 🎉".bright_green().to_string()); - } -} diff --git a/src/tui/mod.rs b/src/tui/mod.rs deleted file mode 100644 index 03d6911..0000000 --- a/src/tui/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod display; -pub use display::TerminalHud; diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..57b58f9 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,18 @@ +"""Hermetic test fixtures ensuring no test ever touches real %APPDATA% or system hosts.""" + +from __future__ import annotations + +from pathlib import Path +import pytest + + +@pytest.fixture(autouse=True) +def hermetic_focusflow_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]: + state_dir = tmp_path / "focusflow_state" + state_dir.mkdir(parents=True, exist_ok=True) + hosts_file = tmp_path / "hosts" + hosts_file.write_text("127.0.0.1 localhost\n::1 localhost\n", encoding="utf-8") + + monkeypatch.setenv("FOCUSFLOW_HOME", str(state_dir)) + monkeypatch.setenv("FOCUSFLOW_HOSTS_PATH", str(hosts_file)) + return state_dir, hosts_file diff --git a/tests/test_config_sessions_interop.py b/tests/test_config_sessions_interop.py new file mode 100644 index 0000000..c7bfeca --- /dev/null +++ b/tests/test_config_sessions_interop.py @@ -0,0 +1,151 @@ +"""Cross-runtime schema & state-directory interoperability tests between Go CLI and Python.""" + +from __future__ import annotations + +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess + +from focusflow_core.config import ConfigStore, default_profiles, load_config, load_or_default, save_config +from focusflow_core.hosts import HostsManager, SessionMeta +from focusflow_core.paths import get_config_path, get_state_dir +from focusflow_core.storage import SessionStore + + +def _find_go_binary() -> str | None: + found = shutil.which("go") + if found: + return found + win_default = Path(r"C:\Program Files\Go\bin\go.exe") + if win_default.exists(): + return str(win_default) + return None + + +def test_config_migration_and_schema_roundtrip(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, _ = hermetic_focusflow_env + assert Path(get_state_dir()) == state_dir + + # Write legacy keys and protected binaries; verify clean migration to custom_domains / custom_processes + cfg_path = Path(get_config_path()) + cfg_path.write_text( + json.dumps( + { + "custom_sites": ["https://www.DistractSite.com/news", "localhost", "127.0.0.1"], + "custom_apps": ["EpicGamesLauncher", "explorer.exe", "pythonw.exe"], + } + ), + encoding="utf-8", + ) + + cfg = load_config() + assert cfg.custom_domains == ["distractsite.com"] + assert cfg.custom_processes == ["epicgameslauncher.exe"] + save_config(cfg) + + saved_raw = json.loads(cfg_path.read_text(encoding="utf-8")) + assert set(saved_raw.keys()) == {"custom_domains", "custom_processes", "profiles"} + assert set(saved_raw["profiles"].keys()) >= {"study", "dev", "hardcore"} + + dev_merged = load_or_default("dev") + assert "distractsite.com" in dev_merged.blocked_domains + assert "epicgameslauncher.exe" in dev_merged.blocked_processes + + +def test_go_and_python_full_state_interoperability(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + go_bin = _find_go_binary() + + # Create config & session records from Python + cfg = ConfigStore( + custom_domains=["news.ycombinator.com"], + custom_processes=["battle.net.exe"], + profiles=default_profiles(), + ) + save_config(cfg, state_dir=str(state_dir)) + + store = SessionStore(state_dir=str(state_dir)) + now = datetime.datetime.now(datetime.timezone.utc) + store.start_session("interop-1", "dev", 50, start_time=now - datetime.timedelta(minutes=50)) + store.finalize_session( + "interop-1", + "dev", + 50, + completed=True, + blocked_count=3, + start_time=now - datetime.timedelta(minutes=50), + end_time=now, + ) + + if go_bin is None: + return + + repo_root = Path(__file__).resolve().parent.parent + env = os.environ.copy() + env["FOCUSFLOW_HOME"] = str(state_dir) + env["FOCUSFLOW_HOSTS_PATH"] = str(hosts_path) + env["CGO_ENABLED"] = "0" + go_dir = str(Path(go_bin).parent) + env["PATH"] = f"{go_dir}{os.pathsep}{env.get('PATH', '')}" + + # 1. Verify Go CLI reads Python-written config.json seamlessly + res_list = subprocess.run( + [go_bin, "run", "./cmd/focusflow", "list", "--json"], + cwd=str(repo_root), + env=env, + capture_output=True, + text=True, + check=True, + ) + go_list = json.loads(res_list.stdout) + assert go_list["custom_domains"] == ["news.ycombinator.com"] + assert go_list["custom_processes"] == ["battle.net.exe"] + + # 2. Verify Go CLI computes identical stats from Python-written sessions.json + res_stats = subprocess.run( + [go_bin, "run", "./cmd/focusflow", "stats", "--days", "7", "--json"], + cwd=str(repo_root), + env=env, + capture_output=True, + text=True, + check=True, + ) + go_stats = json.loads(res_stats.stdout) + py_stats = store.compute_analytics(days=7) + assert go_stats["completed_sprints"] == py_stats.completed_sprints == 1 + assert go_stats["total_minutes"] == py_stats.total_minutes == 50 + assert go_stats["active_streak_days"] == py_stats.active_streak_days == 1 + + # 3. Simulate Python orphan crash and verify Go `doctor --json` auto-recovers hosts & sessions.json! + store.start_session("py-crash-404", "hardcore", 25, start_time=now - datetime.timedelta(minutes=5)) + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + hm.apply_blocklist( + ["tiktok.com"], + meta=SessionMeta( + session_id="py-crash-404", + pid=99999999, + started_at=now - datetime.timedelta(minutes=5), + expected_end_at=now + datetime.timedelta(minutes=20), + profile="hardcore", + ), + ) + assert hm.is_active() + + res_doc = subprocess.run( + [go_bin, "run", "./cmd/focusflow", "doctor", "--json"], + cwd=str(repo_root), + env=env, + capture_output=True, + text=True, + check=True, + ) + doc_json = json.loads(res_doc.stdout) + assert doc_json["recovery"]["recovered"] is True + assert not hm.is_active() + + sessions = {s.id: s for s in store.load_sessions()} + assert sessions["py-crash-404"].completed is False + assert sessions["py-crash-404"].status == "orphaned" diff --git a/tests/test_engine.rs b/tests/test_engine.rs deleted file mode 100644 index 241d061..0000000 --- a/tests/test_engine.rs +++ /dev/null @@ -1,65 +0,0 @@ -use focusflow::engine::HostsManager; -use focusflow::profile::FocusProfile; -use focusflow::storage::Database; -use std::fs; -use tempfile::NamedTempFile; - -#[test] -fn test_hosts_atomic_apply_and_rollback() { - // Create temporary mock hosts file - let temp_hosts = NamedTempFile::new().expect("Failed to create temp hosts file"); - let initial_content = "127.0.0.1 localhost\n::1 localhost\n"; - fs::write(temp_hosts.path(), initial_content).expect("Failed to write initial hosts"); - - let initial_hash = HostsManager::compute_sha256(temp_hosts.path()).expect("Hash calculation failed"); - - let manager = HostsManager::with_path(temp_hosts.path().to_path_buf()); - - // Apply blocklist - let domains = vec!["instagram.com".to_string(), "tiktok.com".to_string()]; - manager.apply_blocklist(&domains).expect("Failed to apply blocklist"); - - assert!(manager.is_active(), "Manager should report active"); - - let modified_content = fs::read_to_string(temp_hosts.path()).expect("Failed to read modified hosts"); - assert!(modified_content.contains("0.0.0.0 instagram.com")); - assert!(modified_content.contains("0.0.0.0 www.instagram.com")); - assert!(modified_content.contains("0.0.0.0 tiktok.com")); - - // Rollback - manager.rollback().expect("Failed to rollback"); - - assert!(!manager.is_active(), "Manager should report inactive after rollback"); - - let restored_hash = HostsManager::compute_sha256(temp_hosts.path()).expect("Restored hash failed"); - assert_eq!(initial_hash, restored_hash, "Restored hosts file must match original hash byte-for-byte!"); -} - -#[test] -fn test_database_in_memory_metrics() { - let db = Database::open_in_memory().expect("Failed to open in-memory DB"); - - // Record two successful sessions - db.record_session("dev", 50, true, 5).expect("Record 1 failed"); - db.record_session("study", 25, true, 2).expect("Record 2 failed"); - - // Record one failed/aborted session (should not count in completed) - db.record_session("dev", 10, false, 1).expect("Record 3 failed"); - - let (total_sessions, total_minutes, total_blocked) = db.get_total_stats().expect("Stats query failed"); - assert_eq!(total_sessions, 2); - assert_eq!(total_minutes, 75); - assert_eq!(total_blocked, 7); -} - -#[test] -fn test_profiles_structure() { - let dev = FocusProfile::dev_profile(); - assert_eq!(dev.name, "dev"); - assert!(dev.blocked_domains.contains(&"twitter.com".to_string())); - assert!(dev.blocked_processes.contains(&"discord.exe".to_string())); - - let study = FocusProfile::study_profile(); - assert_eq!(study.name, "study"); - assert!(study.blocked_domains.contains(&"youtube.com".to_string())); -} diff --git a/tests/test_hosts_journal.py b/tests/test_hosts_journal.py new file mode 100644 index 0000000..3c7a43d --- /dev/null +++ b/tests/test_hosts_journal.py @@ -0,0 +1,214 @@ +"""Tests for crash-safe SHA-256 hosts engine, write-ahead journal, ACLs, and orphan recovery.""" + +from __future__ import annotations + +import datetime +import os +from pathlib import Path +import subprocess +import sys + +from focusflow_core.hosts import ( + LEGACY_MARKER_BEGIN, + LEGACY_MARKER_END, + MARKER_BEGIN, + MARKER_END, + HostsManager, + SessionMeta, + has_managed_markers, + strip_managed_blocks, +) +from focusflow_core.storage import SessionStore + + +def test_atomic_dual_stack_apply_journal_and_rollback(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + initial_sha = hm.compute_sha256(str(hosts_path)) + + now = datetime.datetime.now(datetime.timezone.utc) + meta = SessionMeta( + session_id="py-sess-001", + pid=os.getpid(), + started_at=now, + expected_end_at=now + datetime.timedelta(minutes=25), + profile="study", + ) + + assert hm.apply_blocklist(["https://www.Instagram.com/explore", "tiktok.com:443"], meta=meta) + assert hm.is_active() + + journal = hm.load_journal() + assert journal is not None + assert journal.original_sha256 == initial_sha + assert journal.session_id == "py-sess-001" + assert journal.pid == os.getpid() + assert journal.profile == "study" + assert os.path.exists(journal.backup_path) + + content = hosts_path.read_text(encoding="utf-8") + for expected in ( + MARKER_BEGIN, + "0.0.0.0 instagram.com", + "0.0.0.0 www.instagram.com", + ":: instagram.com", + ":: www.instagram.com", + "0.0.0.0 tiktok.com", + "0.0.0.0 www.tiktok.com", + ":: tiktok.com", + ":: www.tiktok.com", + MARKER_END, + ): + assert expected in content + + hm.rollback() + assert not hm.is_active() + assert not os.path.exists(hm.journal_path) + assert not os.path.exists(hm.backup_path) + assert hm.compute_sha256(str(hosts_path)) == initial_sha + + +def test_never_backup_contaminated_hosts(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + clean_base = "127.0.0.1 localhost\r\n192.168.1.99 workstation.lan\r\n" + contaminated = ( + clean_base + + "\r\n" + + f"{LEGACY_MARKER_BEGIN}\r\n127.0.0.1 youtube.com\r\n{LEGACY_MARKER_END}\r\n\r\n" + + f"{MARKER_BEGIN}\r\n0.0.0.0 reddit.com\r\n{MARKER_END}\r\n" + ) + hosts_path.write_bytes(contaminated.encode("utf-8")) + + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + hm.apply_blocklist(["x.com"]) + + bak_content = Path(hm.backup_path).read_bytes().decode("utf-8") + assert not has_managed_markers(bak_content) + assert bak_content == clean_base + + hm.rollback() + assert hosts_path.read_bytes().decode("utf-8") == clean_base + + +def test_missing_end_marker_safe_stripping_no_corruption() -> None: + truncated_current = ( + "127.0.0.1 localhost\n::1 localhost\n\n" + f"{MARKER_BEGIN}\n# FocusFlow v2.1 - Dual-Stack Managed Sinkhole\n" + "0.0.0.0 youtube.com\n:: youtube.com\n" + ) + assert strip_managed_blocks(truncated_current) == "127.0.0.1 localhost\n::1 localhost\n" + + truncated_legacy_with_custom = ( + "127.0.0.1 localhost\r\n\r\n" + f"{LEGACY_MARKER_BEGIN}\r\n127.0.0.1 instagram.com\r\n" + "10.0.0.25 internal.corp\r\n" + ) + assert strip_managed_blocks(truncated_legacy_with_custom) == "127.0.0.1 localhost\r\n10.0.0.25 internal.corp\r\n" + + +def test_crlf_and_lf_line_ending_preservation(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + crlf_base = b"127.0.0.1 localhost\r\n::1 localhost\r\n" + hosts_path.write_bytes(crlf_base) + + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + hm.apply_blocklist(["reddit.com"]) + raw_after = hosts_path.read_bytes() + assert b"\r\n0.0.0.0 reddit.com\r\n" in raw_after + assert b"\r\n:: reddit.com\r\n" in raw_after + + hm.rollback() + assert hosts_path.read_bytes() == crlf_base + + +def test_recover_if_orphaned_dead_pid_expired_and_corrupt_bak_fallback( + hermetic_focusflow_env: tuple[Path, Path], +) -> None: + state_dir, hosts_path = hermetic_focusflow_env + clean_text = "127.0.0.1 localhost\n::1 localhost\n" + hosts_path.write_text(clean_text, encoding="utf-8") + + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + store = SessionStore(state_dir=str(state_dir)) + now = datetime.datetime.now(datetime.timezone.utc) + + # 1. Active current PID with future lease must not be clobbered + hm.apply_blocklist( + ["reddit.com"], + meta=SessionMeta( + session_id="live-1", + pid=os.getpid(), + started_at=now, + expected_end_at=now + datetime.timedelta(minutes=30), + profile="dev", + ), + ) + res_live = hm.recover_if_orphaned(now=now, flush_async=False) + assert not res_live.recovered + assert res_live.active_owner_pid == os.getpid() + + # 2. Dead PID + tampered .bak triggers deterministic marker-stripping fallback + marks session orphaned + store.start_session("dead-sess-88", "hardcore", 25, start_time=now - datetime.timedelta(minutes=10)) + hm.apply_blocklist( + ["reddit.com", "twitch.tv"], + meta=SessionMeta( + session_id="dead-sess-88", + pid=99999999, + started_at=now - datetime.timedelta(minutes=10), + expected_end_at=now + datetime.timedelta(minutes=15), + profile="hardcore", + ), + ) + Path(hm.backup_path).write_text("corrupted-backup-contents", encoding="utf-8") + + res_dead = hm.recover_if_orphaned( + on_orphan_session=lambda sid: store.mark_orphaned_session(sid, now=now), + now=now, + flush_async=False, + ) + assert res_dead.recovered + assert res_dead.used_fallback + assert res_dead.orphan_session_id == "dead-sess-88" + assert hosts_path.read_text(encoding="utf-8") == clean_text + + sessions = store.load_sessions() + assert len(sessions) == 1 + assert sessions[0].id == "dead-sess-88" + assert sessions[0].completed is False + assert sessions[0].status == "orphaned" + + +def test_verify_or_reapply_mid_session_watchdog(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + clean_text = "127.0.0.1 localhost\n" + hosts_path.write_text(clean_text, encoding="utf-8") + + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + domains = ["youtube.com", "netflix.com"] + hm.apply_blocklist(domains) + assert hm.verify_or_reapply(domains) is False + + # Simulate external tampering mid-sprint + hosts_path.write_text(clean_text, encoding="utf-8") + assert hm.verify_or_reapply(domains) is True + assert hm.is_active() + + hm.rollback() + assert hosts_path.read_text(encoding="utf-8") == clean_text + + +def test_permissions_and_windows_acl_preservation(hermetic_focusflow_env: tuple[Path, Path]) -> None: + state_dir, hosts_path = hermetic_focusflow_env + hosts_path.write_bytes(b"127.0.0.1 localhost\r\n") + hm = HostsManager(hosts_path=str(hosts_path), state_dir=str(state_dir)) + + if sys.platform == "win32": + subprocess.run(["icacls", str(hosts_path), "/grant", "*S-1-5-32-545:(R)"], check=False, capture_output=True) + before = subprocess.run(["icacls", str(hosts_path)], check=True, capture_output=True, text=True).stdout + hm.apply_blocklist(["example.com"]) + after = subprocess.run(["icacls", str(hosts_path)], check=True, capture_output=True, text=True).stdout + assert before == after + else: + os.chmod(hosts_path, 0o644) + hm.apply_blocklist(["example.com"]) + assert (os.stat(hosts_path).st_mode & 0o777) == 0o644 diff --git a/tests/test_sanitization.py b/tests/test_sanitization.py new file mode 100644 index 0000000..4bee59e --- /dev/null +++ b/tests/test_sanitization.py @@ -0,0 +1,127 @@ +"""Tests for RFC-1123 domain sanitization, Anti-DoH domains, and protected process denylist.""" + +from __future__ import annotations + +import pytest + +from focusflow_core.sanitize import ( + DOH_BYPASS_DOMAINS, + DomainValidationError, + ProcessValidationError, + is_protected_process, + normalize_process_name, + sanitize_domain, + sanitize_domains, +) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("youtube.com", "youtube.com"), + (" HTTPS://www.YouTube.com:443/watch?v=123#top ", "youtube.com"), + ("http://Sub.Reddit.com:8080/r/python/", "sub.reddit.com"), + ("x.com.", "x.com"), + ("dns.adguard-dns.com", "dns.adguard-dns.com"), + ("one.one.one.one", "one.one.one.one"), + ], +) +def test_sanitize_domain_valid(raw: str, expected: str) -> None: + assert sanitize_domain(raw) == expected + + +@pytest.mark.parametrize( + "bad_raw", + [ + "", + " ", + "# comment", + "evil.com\n127.0.0.1 bank.com", + "evil.com\r\n0.0.0.0 github.com", + "evil.com\tinjected.com", + "evil.com injected.com", + "evil\x00.com", + "127.0.0.1", + "0.0.0.0", + "192.168.1.1", + "999.999.999.999", + "::1", + "[::1]:8080", + "2001:db8::1", + "localhost", + "LOCALHOST", + "localdomain", + "localhost.localdomain", + "printer.local", + "dev.localhost", + "box.localdomain", + "singlelabel", + "-bad.com", + "bad-.com", + "bad..dots.com", + "example.com:99999", + "example.com:abc", + "ftp://example.com", + "user@example.com", + ], +) +def test_sanitize_domain_rejects_unsafe_inputs(bad_raw: str) -> None: + with pytest.raises(DomainValidationError): + sanitize_domain(bad_raw) + + +def test_sanitize_domains_deduplicates_deterministically() -> None: + cleaned = sanitize_domains( + ["https://www.Twitter.com/home", "twitter.com", "localhost", "127.0.0.1", "reddit.com"] + ) + assert cleaned == ["twitter.com", "reddit.com"] + + +def test_expanded_doh_bypass_domains_present() -> None: + required = { + "cloudflare-dns.com", + "dns.google", + "dns.quad9.net", + "doh.opendns.com", + "dns.adguard-dns.com", + "dns.nextdns.io", + "doh.cleanbrowsing.org", + "doh.dns.sb", + "freedns.controld.com", + } + assert required.issubset(set(DOH_BYPASS_DOMAINS)) + + +@pytest.mark.parametrize( + "proc_name", + [ + "csrss.exe", + "smss.exe", + "lsass.exe", + "services.exe", + "svchost.exe", + "wininit.exe", + "winlogon.exe", + "dwm.exe", + "explorer.exe", + "sihost.exe", + "fontdrvhost.exe", + "focusflow.exe", + "python.exe", + "pythonw.exe", + "conhost.exe", + "wt.exe", + "EXPLORER", + "PythonW", + r"C:\Windows\System32\svchost.exe", + ], +) +def test_protected_process_denylist(proc_name: str) -> None: + assert is_protected_process(proc_name) + with pytest.raises(ProcessValidationError): + normalize_process_name(proc_name) + + +def test_normalize_process_name_valid() -> None: + assert normalize_process_name(" Discord ") == "discord.exe" + assert normalize_process_name("Steam.EXE") == "steam.exe" diff --git a/tests/test_supervisor.py b/tests/test_supervisor.py new file mode 100644 index 0000000..f3babd0 --- /dev/null +++ b/tests/test_supervisor.py @@ -0,0 +1,109 @@ +"""Tests for zero-dependency Win32/POSIX process supervisor, denylist, and elevation cmdline.""" + +from __future__ import annotations + +import os +from pathlib import Path +import subprocess +import sys +import time + +from focusflow_core.privileges import build_elevation_cmdline, shield_mode_label +from focusflow_core.supervisor import ( + AntiCheatGuard, + ProcessSupervisor, + is_pid_alive, + resolve_procfs_names, +) + + +def test_supervisor_denylist_and_protected_pids() -> None: + killed: list[int] = [] + fake_procs = [ + (0, ["System Idle Process"]), + (4, ["System"]), + (os.getpid(), ["discord.exe"]), + (os.getppid(), ["discord.exe"]), + (1200, ["explorer.exe"]), + (1300, ["svchost.exe"]), + (1400, ["python.exe"]), + (1500, ["focusflow.exe"]), + (4242, ["Discord.exe"]), + ] + sup = ProcessSupervisor( + blocked=["discord.exe", "explorer.exe", "svchost.exe", "python.exe", "focusflow.exe"], + enumerator=lambda: fake_procs, + terminator=lambda pid: (killed.append(pid) or True), + ) + + result = sup.scan_and_terminate() + assert killed == [4242] + assert result == ["Discord.exe (PID: 4242)"] + + +def test_anticheat_guard_includes_system_informer() -> None: + ac = AntiCheatGuard("hardcore") + for expected in ("taskmgr.exe", "processhacker.exe", "systeminformer.exe", "procmon.exe", "procexp.exe"): + assert expected in ac.supervisor.blocked_names + + ac_std = AntiCheatGuard("standard") + assert len(ac_std.supervisor.blocked_names) == 0 + + +def test_linux_procfs_15_byte_comm_truncation(tmp_path: Path) -> None: + proc_root = tmp_path / "proc" + pid_dir = proc_root / "54321" + pid_dir.mkdir(parents=True) + # 15-byte truncated TASK_COMM_LEN + (pid_dir / "comm").write_text("riotclientservi\n", encoding="utf-8") + (pid_dir / "cmdline").write_bytes(b"/opt/riot/RiotClientServices.exe\x00--launch\x00") + + cands = resolve_procfs_names(str(proc_root), "54321") + sup = ProcessSupervisor(["riotclientservices.exe"]) + assert sup.should_terminate(54321, cands) == "RiotClientServices.exe" + + +def test_live_native_process_enumeration_and_termination_zero_psutil() -> None: + assert is_pid_alive(os.getpid()) is True + assert is_pid_alive(99999999) is False + + # Spawn a harmless standard OS utility process ("ping" on Windows, "sleep" on POSIX) + # and terminate it via native zero-dependency Win32 Toolhelp32 / POSIX supervisor! + if sys.platform == "win32": + child = subprocess.Popen( + ["ping.exe", "-n", "30", "127.0.0.1"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + creationflags=0x08000000, + ) + target_name = "ping.exe" + else: + child = subprocess.Popen( + ["sleep", "30"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + target_name = "sleep" + + try: + time.sleep(0.15) + assert is_pid_alive(child.pid) + sup = ProcessSupervisor([target_name]) + terminated = sup.scan_and_terminate() + child.wait(timeout=5) + assert any(str(child.pid) in entry for entry in terminated) + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=3) + + +def test_elevation_cmdline_quotes_spaces_and_honest_shield_labels() -> None: + cmd = build_elevation_cmdline( + script_path=r"C:\Users\Asaf Arda\Desktop\FocusFlow\FocusFlowGUI.py", + extra_args=["--profile", "hardcore mode"], + ) + assert '"C:\\Users\\Asaf Arda\\Desktop\\FocusFlow\\FocusFlowGUI.py"' in cmd or "Asaf Arda" in cmd + assert '"hardcore mode"' in cmd + assert shield_mode_label(True) == "FULL SHIELD [HOSTS + PROC]" + assert shield_mode_label(False) == "PROCESS-ONLY [UNPRIVILEGED]" diff --git a/tests/test_timer_analytics.py b/tests/test_timer_analytics.py new file mode 100644 index 0000000..845c12f --- /dev/null +++ b/tests/test_timer_analytics.py @@ -0,0 +1,220 @@ +"""Tests for monotonic deadline timer, friction challenge, real analytics, and zero-emoji compliance.""" + +from __future__ import annotations + +import datetime +import json +from pathlib import Path +import re + +from focusflow_core.storage import SessionStore +from focusflow_core.timer import FRICTION_ALPHABET, MonotonicPhaseTimer, generate_friction_token + + +def test_monotonic_timer_zero_drift_and_no_modal_break_burn() -> None: + fake_now = [1000.0] + timer = MonotonicPhaseTimer(clock_fn=lambda: fake_now[0]) + + timer.start(1500.0, phase="WORK") + assert timer.remaining_seconds() == 1500 + assert timer.poll_expired() is False + + fake_now[0] += 750.0 + assert timer.remaining_seconds() == 750 + assert abs(timer.progress_ratio() - 0.5) < 1e-6 + + # Pause & resume without drift + timer.pause() + fake_now[0] += 300.0 + assert timer.remaining_seconds() == 750 + timer.resume() + + # Expire WORK phase + fake_now[0] += 750.0 + assert timer.poll_expired() is True + assert timer.awaiting_transition is True + # Subsequent polls while modal dialog is open must NOT fire duplicate expirations! + fake_now[0] += 600.0 # User leaves modal open for 10 minutes + assert timer.poll_expired() is False + + # User clicks OK on modal -> 5-minute break starts fresh with full 300s! + timer.start(300.0, phase="BREAK") + assert timer.remaining_seconds() == 300 + + +def test_friction_token_properties() -> None: + tokens = {generate_friction_token(16) for _ in range(25)} + assert len(tokens) == 25 + for tok in tokens: + assert len(tok) == 16 + assert all(ch in FRICTION_ALPHABET for ch in tok) + assert not any(amb in tok for amb in ("0", "O", "1", "I")) + + +def test_real_analytics_no_fake_seed_and_streak_calculation( + hermetic_focusflow_env: tuple[Path, Path], +) -> None: + state_dir, _ = hermetic_focusflow_env + store = SessionStore(state_dir=str(state_dir)) + + # Empty store must report 0 streak, 0 minutes, 0% completion + empty = store.compute_analytics(days=7) + assert empty.active_streak_days == 0 + assert empty.total_minutes == 0 + assert empty.completed_sprints == 0 + assert empty.completion_rate == 0.0 + assert len(empty.daily) == 7 + assert all(d.minutes == 0 for d in empty.daily) + + ref = datetime.datetime(2026, 11, 10, 18, 0, 0, tzinfo=datetime.timezone.utc) + d2 = ref - datetime.timedelta(days=2) + d1 = ref - datetime.timedelta(days=1) + + store.finalize_session("s1", "study", 25, completed=True, blocked_count=1, start_time=d2, end_time=d2) + store.finalize_session("s2", "dev", 50, completed=True, blocked_count=2, start_time=d1, end_time=d1) + sid3 = store.start_session("s3", "study", 45, start_time=ref - datetime.timedelta(minutes=45)) + store.finalize_session( + sid3, + "study", + 45, + completed=True, + blocked_count=4, + start_time=ref - datetime.timedelta(minutes=45), + end_time=ref, + ) + # Aborted session recorded as completed=False + store.finalize_session( + "s4", + "hardcore", + 10, + completed=False, + blocked_count=3, + start_time=ref - datetime.timedelta(minutes=10), + end_time=ref, + ) + + summary = store.compute_analytics(days=7, now=ref) + assert summary.completed_sprints == 3 + assert summary.attempted_sprints == 4 + assert summary.aborted_sprints == 1 + assert summary.completion_rate == 75.0 + assert summary.total_minutes == 120 + assert summary.total_hours == 2.0 + assert summary.active_streak_days == 3 + assert summary.total_blocked == 10 + + exported = json.loads(store.export_json_string(days=7, now=ref)) + assert exported["summary"]["active_streak_days"] == 3 + csv_text = store.export_csv_string() + assert "s1,study" in csv_text + assert "s4,hardcore" in csv_text + + +def test_zero_emoji_and_zero_shortcode_across_code_and_docs() -> None: + repo_root = Path(__file__).resolve().parent.parent + targets = [ + "FocusFlowGUI.py", + "cmd/focusflow/main.go", + "pkg/tui/hud.go", + "README.md", + "README.tr.md", + "SECURITY.md", + "CHANGELOG.md", + "CONTRIBUTING.md", + ] + shortcode_re = re.compile(r":[a-z0-9_+-]+:") + + for rel in targets: + p = repo_root / rel + text = p.read_text(encoding="utf-8") + for ch in text: + cp = ord(ch) + is_emoji = ( + (0x1F000 <= cp <= 0x1FAFF) + or (0x2600 <= cp <= 0x27BF) + or cp == 0xFE0F + ) + assert not is_emoji, f"Forbidden emoji/dingbat U+{cp:04X} ({ch!r}) found in {rel}" + + # Exclude URL schemes like https: or port specs by checking GitHub emoji shortcodes + for match in shortcode_re.finditer(text): + token = match.group(0) + assert token not in (":white_check_mark:", ":x:", ":warning:", ":rocket:", ":fire:"), ( + f"Forbidden emoji shortcode {token} found in {rel}" + ) + + +def test_gui_profile_switching_strict_close_and_single_prompt_unlock( + hermetic_focusflow_env: tuple[Path, Path], + monkeypatch, +) -> None: + import pytest + + tk = pytest.importorskip("tkinter") + import FocusFlowGUI + + try: + root = tk.Tk() + root.withdraw() + except tk.TclError: + pytest.skip("Tkinter display unavailable in headless environment") + + app = FocusFlowGUI.FocusFlowGUI(root) + try: + # 1. Profile switching dynamically updates intervals, rules, and strictness + app.profile_var.set("dev") + app.on_profile_change() + assert app.current_profile == "dev" + assert app.gui_prefs["pomo_work"] == 50 + assert app.gui_prefs["pomo_break"] == 10 + assert "youtube.com" not in app.active_profile_obj.blocked_domains + + app.profile_var.set("hardcore") + app.on_profile_change() + assert app.current_profile == "hardcore" + assert app.is_strict_active() is True + assert app.current_strictness_level() == "hardcore" + assert "youtube.com" in app.active_profile_obj.blocked_domains + + # 2. Start session -> StartTime persisted immediately in sessions.json + app.start_session() + assert app.is_active is True + running = app.session_store.load_sessions() + assert len(running) == 1 + assert running[0].status == "running" + + # 3. Window close (X) in strict mode MUST invoke Friction Challenge and block close on failure + challenge_calls = [] + + def fake_fail_challenge(reason: str = "") -> bool: + challenge_calls.append(reason) + return False + + monkeypatch.setattr(app, "_verify_friction_challenge", fake_fail_challenge) + app.on_close() + assert len(challenge_calls) == 1 + assert app.is_active is True # Window close bypass blocked! + + # 4. Emergency unlock invokes Friction Challenge ONCE (no double-prompt bug!) and records completed=False + prompt_count = [0] + + def fake_pass_challenge(reason: str = "") -> bool: + prompt_count[0] += 1 + return True + + monkeypatch.setattr(app, "_verify_friction_challenge", fake_pass_challenge) + app.prompt_emergency() + assert prompt_count[0] == 1 + assert app.is_active is False + + finalized = app.session_store.load_sessions() + assert len(finalized) == 1 + assert finalized[0].completed is False + assert finalized[0].status == "aborted" + finally: + app.worker_running = False + try: + root.destroy() + except Exception: + pass +