From e4f85f40c5616622cec2d33b690fefd70851d201 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:44:33 +0000 Subject: [PATCH 1/7] Install with one Python program instead of three shell scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The installer was three scripts with three sets of answers: setup.sh knew APT, setup_termux.sh knew pkg, setup_windows.ps1 knew winget, and each had its own sentence for a missing Python or a missing tunnel. Fixing a step meant fixing it three times, and the Windows script had grown four of its own switches that the other platforms never got. Now `./nerveforge install` runs the same ten steps everywhere — Python, rights, tunnel, download, folders, workspace, shortcut, command, check, start — and each step prints one line saying what it found or why it stopped, with a remedy under it. The steps live in installer/actions.py, the questions in menu.py, the output in render.py. The flags keep three promises: --plan goes through the same step table and changes nothing, so it cannot drift from the run; --yes answers the defaults, which are quiet (the PATH launcher is offered, never assumed); --uninstall removes the shortcut, launcher and downloaded cloudflared and says out loud that the token, settings, skills and audit log were kept. The old entry points still work: setup.sh, setup_termux.sh and setup_windows.ps1 now find a Python 3.10+ and hand over, and run.py starts the bridge as before, so an older README or shortcut does not break. InstallerTests read setup_windows.ps1 and asserted on its BOM, its chr(46) trick and its brace balance — tests of a script, not an installer. They are replaced by 64 tests that run the real steps against a temporary HOME. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/ci.yml | 8 +- CHANGELOG.md | 58 +++ README.md | 75 ++-- SECURITY.md | 2 +- VERSION | 2 +- docs/DEVELOPMENT.md | 6 +- docs/ru/CHANGELOG.md | 57 +++ docs/ru/DEVELOPMENT.md | 6 +- docs/ru/README.md | 79 ++-- docs/ru/SECURITY.md | 2 +- nerveforge | 41 ++ run.py | 12 +- scripts/bump_version.py | 3 +- setup.sh | 65 +-- setup_termux.sh | 27 +- setup_windows.ps1 | 320 ++------------- src/nerveforge/_version.py | 2 +- src/nerveforge/installer/__init__.py | 34 ++ src/nerveforge/installer/actions.py | 359 +++++++++++++++++ src/nerveforge/installer/apps.py | 197 +++++++++ src/nerveforge/installer/cli.py | 209 ++++++++++ src/nerveforge/installer/detect.py | 184 +++++++++ src/nerveforge/installer/menu.py | 149 +++++++ src/nerveforge/installer/render.py | 147 +++++++ src/nerveforge/installer/steps.py | 142 +++++++ tests/test_installer.py | 574 +++++++++++++++++++++++++++ tests/test_static_panel.py | 61 --- 27 files changed, 2336 insertions(+), 485 deletions(-) create mode 100755 nerveforge mode change 100644 => 100755 run.py mode change 100644 => 100755 setup.sh mode change 100644 => 100755 setup_termux.sh create mode 100644 src/nerveforge/installer/__init__.py create mode 100644 src/nerveforge/installer/actions.py create mode 100644 src/nerveforge/installer/apps.py create mode 100644 src/nerveforge/installer/cli.py create mode 100644 src/nerveforge/installer/detect.py create mode 100644 src/nerveforge/installer/menu.py create mode 100644 src/nerveforge/installer/render.py create mode 100644 src/nerveforge/installer/steps.py create mode 100644 tests/test_installer.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 985e61b..1a70cb0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,8 +41,12 @@ jobs: python scripts/gen_api_doc.py --check python scripts/bump_version.py --check python scripts/check_docs.py - - name: Shell installer syntax - run: bash -n setup.sh + - name: Shell scripts and entry points + run: | + bash -n setup.sh + bash -n setup_termux.sh + python -m compileall -q nerveforge + python nerveforge install --plan > /dev/null windows: runs-on: windows-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 69d5bfd..bd4d94a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,64 @@ **English** · [Русский](docs/ru/CHANGELOG.md) +## 8.7.0 + +The installer stops being three shell scripts that each grew their own answers +and becomes one Python program with the same steps everywhere. That is a +smaller change than it sounds, and a more useful one than it looks: the old +scripts were not wrong, they were separate. `setup.sh` knew about APT, +`setup_termux.sh` about `pkg`, `setup_windows.ps1` about `winget`, and each had +its own idea of what "Python is missing" or "the tunnel is not installed" +should say. + +### One program, ten steps, one place to fix a step + +`./nerveforge install` runs the same ten steps on Linux, macOS, Windows and +Termux: Python version, administrator rights, tunnel choice, tunnel download, +config and data folders, the working folder, a shortcut, a `nerveforge` +command, a program check, and the start. Each step prints one line saying what +it found — a path, a version, a reason — and the run stops at the first step +that cannot go on, with a remedy on the line below it. A step that fails but +does not block anything (a blocked `cloudflared` download on a machine that +works fine locally) says so and lets the rest continue. + +The ten steps live in `installer/actions.py`, the questions in `menu.py`, the +rendering in `render.py`. A new step is a function and an entry in one tuple; +there is no second script to bring in line. + +### Three promises the flags keep + +- **`--plan` changes nothing.** It goes through the same step table and prints + only the steps that would change the machine, so the plan cannot drift from + the run. +- **`--yes` answers the defaults, and the defaults are quiet.** Shortcuts + default to yes on a desktop and skip themselves on a server or in Termux; the + `nerveforge` command defaults to *no* — it is offered, not assumed. On a + headless machine `--yes` installs nothing beyond the folders the bridge needs. +- **`--uninstall` draws the line at the operator's own content.** It removes + the shortcut, the launcher and the downloaded `cloudflared`. It keeps the + token, the settings, the installed skills and the audit log, and says that it + kept them. An uninstall that deleted a token would be a data-loss bug wearing + an installer's clothes. + +### The scripts you have keep working + +`setup.sh`, `setup_termux.sh` and `setup_windows.ps1` are now hand-overs: they +find a Python 3.10+, say which one, and run `nerveforge install` with your +arguments. `run.py` still starts the bridge and `./nerveforge` is the new name +for it, so a shortcut or a README from an earlier version does not break. The +Windows script lost its own `winget` logic and its four switches: flags belong +in `nerveforge install`, where every platform gets them. + +### Tests + +`InstallerTests` used to read `setup_windows.ps1` and assert on its BOM, its +`chr(46)` trick and its brace balance — tests of a script, not of an installer. +They are replaced by 64 tests that run the real steps against a temporary +`HOME`: an old Python fails with the reason, a relative workspace is refused, a +declined download is a skip rather than a crash, running twice creates one +shortcut, `--plan` creates nothing, and `--uninstall` keeps the token. + ## 8.6.0 Skills stop being only the twelve that ship here. The Skills screen has a search diff --git a/README.md b/README.md index 0be2918..63c799e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.6.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.7.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](assets/nerveforge-lockup.png) @@ -59,44 +59,52 @@ edit files, build projects and run arbitrary toolchains. ## 🚀 Quick start -### Step 1 — start the receiver +### Step 1 — install and start -Pick your platform: +One command, every platform. The installer is a Python program, so it asks the +same questions and prints the same report on Linux, macOS, Windows and Termux: ```bash -# Linux (Ubuntu / Mint / Debian) git clone https://github.com/foursecondfivefour/NerveForge.git cd NerveForge -bash setup.sh +./nerveforge install # asks a few questions, then starts the bridge ``` -```powershell -# Windows 10 / 11 (PowerShell) -git clone https://github.com/foursecondfivefour/NerveForge.git -cd NerveForge -Set-ExecutionPolicy -Scope Process Bypass -.\setup_windows.ps1 +On Windows use `.\nerveforge install` (or `python nerveforge install`). If the +file is not executable: `python3 nerveforge install`. -# Optional switches -.\setup_windows.ps1 -InstallTunnel # offer cloudflared/Tailscale via winget -.\setup_windows.ps1 -TunnelMode cloudflared # auto (default), cloudflared, tailscale, none -.\setup_windows.ps1 -NoStart # prepare only, do not run -``` - -The installer checks Python, picks a tunnel, asks for the working folder and -runs. Every step says what it found or why it stopped; nothing is installed -without an explicit `Y`. The token and the full-access passphrase are printed in -the startup banner. If the panel says **unauthorized**, the token is missing — -copy it from the banner or paste it on the Settings screen. +It checks Python, asks which tunnel to use, offers to download `cloudflared`, +asks which folder the agent may work in, and then starts the receiver. Every +step prints what it found or why it stopped, and nothing that changes the +machine happens without a `Y` from you. ```bash -# Android (Termux) -git clone https://github.com/foursecondfivefour/NerveForge.git -cd NerveForge -bash setup_termux.sh +./nerveforge install --plan # what it would change, and then stop +./nerveforge install --yes # take the defaults, no questions +./nerveforge install --tunnel none # local only, no public address +./nerveforge install --json --plan # the same plan, for another program ``` -Or on any OS with Python 3.10+: `python3 run.py`. +| Question | Default | +|---|---| +| Tunnel | `auto`: `cloudflared` if present, else Tailscale, else local | +| Download `cloudflared` into the data folder | ask, never silently | +| Working folder for the agent | `~/Projects` | +| Desktop shortcut / menu entry | yes on a desktop, skipped on a server or Termux | +| `nerveforge` command on `PATH` | no — offered, never assumed | +| Start the bridge afterwards | yes | + +The old entry points still work and now hand over to the same installer, so an +older README or a shortcut you keep will not break: `bash setup.sh`, +`bash setup_termux.sh`, `.\setup_windows.ps1`, `python3 run.py`. + +To remove what the installer wrote — shortcut, launcher, downloaded +`cloudflared` — run `./nerveforge uninstall`. Your token, settings, skills and +audit log are kept: those are yours, not the installer's. + +The token and the full-access passphrase are printed in the startup banner. If +the panel says **unauthorized**, the token is missing — copy it from the banner +or paste it on the Settings screen. ### No cloudflared? Let the panel fetch it @@ -249,14 +257,14 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1834 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1894 automated unit tests** (Linux, Windows, Android/Termux, API, security, tunnels). CI runs them on Linux and Windows: ```bash -python3 -m unittest discover -s tests -v # 1834 tests +python3 -m unittest discover -s tests -v # 1894 tests python3 -m compileall -q src tests run.py # Python bytecode find static -name '*.js' -print0 | xargs -0 -n1 node --check # JavaScript syntax # JS syntax -bash -n setup.sh && bash -n setup_termux.sh # shell installers +bash -n setup.sh && bash -n setup_termux.sh # hand-over scripts python3 scripts/gen_api_doc.py --check # docs/API.md is current python3 scripts/bump_version.py --check # version artifacts agree ``` @@ -312,14 +320,17 @@ nerveforge/ │ ├── paths.py # Per-user data and config locations │ ├── platform_support.py # OS detection and shell registry │ ├── toolkit/ # Skills, tool catalogue and installer, MCP client and server +│ ├── installer/ # `nerveforge install`: the ten steps, the menu, the report │ ├── tunnel/ # CLIs, manager and providers (cloudflared/tailscale) │ ├── uzhas_manager.py # Shell runner with timeout and tree cancellation │ └── workspace_manager.py # File operations, bwrap sandbox, public uploads ├── static/ # Web panel assets (HTML, CSS, JS) -├── tests/ # Unit tests (1834 tests) +├── tests/ # Unit tests (1894 tests) ├── pyproject.toml # PEP 517/518 build metadata -├── run.py # Run in place +├── nerveforge # ./nerveforge — start, or `install` step by step +├── run.py # Alias for ./nerveforge (old shortcuts keep working) ├── setup.sh / setup_windows.ps1 / setup_termux.sh +│ # Hand-over scripts: find Python, run `nerveforge install` ├── AGENTS.md # Agent manual ├── CHANGELOG.md # Release history ├── SECURITY.md # Security policy diff --git a/SECURITY.md b/SECURITY.md index 7683355..3122f95 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.6.0 +# Security policy — NerveForge 8.7.0 **English** · [Русский](docs/ru/SECURITY.md) diff --git a/VERSION b/VERSION index acd405b..df5119e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.6.0 +8.7.0 diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 60083a3..39d8c85 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -6,7 +6,8 @@ - Python 3.10 or newer; the application code uses the Python standard library. - Node.js is needed only for the JavaScript syntax check. -- On Windows, PowerShell parses `setup_windows.ps1`; CI performs this check on a Windows runner. +- The installer is Python, so the same steps run on every system; the shell scripts only + find an interpreter and hand over to `./nerveforge install`. - Linux sandbox tests use mocks in CI. To validate real Linux command isolation, test on a supported Mint/Ubuntu host with Bubblewrap and `prlimit` installed. ## Local checks @@ -17,7 +18,8 @@ Run from the repository root: python3 -m unittest discover -s tests -v python3 -m compileall -q src tests run.py find static -name '*.js' -print0 | xargs -0 -n1 node --check -bash -n setup.sh +bash -n setup.sh && bash -n setup_termux.sh +python3 nerveforge install --plan # the installer still runs python3 scripts/gen_api_doc.py --check # docs/API.md is current python3 scripts/bump_version.py --check # every artifact carries one version python3 scripts/check_docs.py # EN/RU stay in step diff --git a/docs/ru/CHANGELOG.md b/docs/ru/CHANGELOG.md index d25895f..8d54583 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -2,8 +2,65 @@ [English](../../CHANGELOG.md) · **Русский** +## 8.7.0 + +Установщик перестаёт быть тремя shell-скриптами, у каждого из которых были свои +ответы, и становится одной программой на Python с одинаковыми шагами везде. Это +меньшее изменение, чем звучит, и более полезное, чем выглядит: старые скрипты не +были неправильными — они были разными. `setup.sh` знал про APT, `setup_termux.sh` +— про `pkg`, `setup_windows.ps1` — про `winget`, и у каждого было своё +представление о том, что говорить при отсутствии Python или туннеля. + +### Одна программа, десять шагов, одно место, где чинить шаг + +`./nerveforge install` проходит одни и те же десять шагов на Linux, macOS, +Windows и Termux: версия Python, права администратора, выбор туннеля, загрузка +туннеля, папки конфигурации и данных, рабочая папка, ярлык, команда +`nerveforge`, проверка программы и запуск. Каждый шаг печатает одну строку о +том, что найдено — путь, версию, причину — и запуск останавливается на первом +шаге, который не может продолжить, с подсказкой строкой ниже. Шаг, который +завершился ошибкой, но ничего не блокирует (заблокированная загрузка +`cloudflared` на машине, которая прекрасно работает локально), говорит об этом и +даёт остальным шагам продолжиться. + +Десять шагов живут в `installer/actions.py`, вопросы — в `menu.py`, вывод — в +`render.py`. Новый шаг — это функция и строка в одном кортеже; второго скрипта, +который надо приводить в соответствие, нет. + +### Три обещания, которые держат ключи + +- **`--plan` ничего не меняет.** Он идёт по той же таблице шагов и печатает + только те, что изменили бы машину, поэтому план не может разойтись с запуском. +- **`--yes` отвечает значениями по умолчанию, и умолчания тихие.** Ярлык по + умолчанию — да на десктопе и пропускается на сервере и в Termux; команда + `nerveforge` по умолчанию — *нет*: её предлагают, а не навязывают. На машине + без графики `--yes` не ставит ничего, кроме папок, нужных мосту. +- **`--uninstall` проводит черту по содержимому самого оператора.** Он убирает + ярлык, лаунчер и скачанный `cloudflared`. Токен, настройки, установленные + скиллы и журнал аудита остаются — и установщик говорит, что оставил их. + Удаление токена при удалении было бы потерей данных в костюме установщика. + +### Скрипты, которые у вас есть, продолжают работать + +`setup.sh`, `setup_termux.sh` и `setup_windows.ps1` теперь только передают +управление: находят Python 3.10+, говорят, какой именно, и запускают +`nerveforge install` с вашими аргументами. `run.py` по-прежнему запускает мост, а +`./nerveforge` — его новое имя, так что ярлык или README прошлой версии ничего не +сломают. Windows-скрипт лишился своей логики `winget` и четырёх ключей: ключи +место в `nerveforge install`, где их получает каждая платформа. + +### Тесты + +`InstallerTests` читали `setup_windows.ps1` и проверяли его BOM, трюк с +`chr(46)` и баланс скобок — тесты скрипта, а не установщика. Их заменили 64 +теста, которые прогоняют настоящие шаги на временном `HOME`: старый Python +падает с причиной, относительная рабочая папка отвергается, отклонённая загрузка +— это пропуск, а не падение, двойной запуск создаёт один ярлык, `--plan` не +создаёт ничего, а `--uninstall` сохраняет токен. + ## 8.6.0 + Скиллы перестают быть только теми двенадцатью, что идут в комплекте. На экране «Навыки» появился поиск по GitHub, ранжирование найденного и установка выбранного — а объяснять стоит именно ранжирование, потому что интересное в diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 3ae5d4e..9ee3d80 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -6,7 +6,8 @@ - Python 3.10 или новее; приложение использует только стандартную библиотеку. - Node.js нужен только для проверки синтаксиса JavaScript. -- На Windows `setup_windows.ps1` разбирает PowerShell; CI выполняет эту проверку на раннере Windows. +- Установщик написан на Python, поэтому одни и те же шаги выполняются на любой системе; + shell-скрипты лишь находят интерпретатор и передают управление `./nerveforge install`. - Тесты песочницы Linux в CI построены на моках. Для проверки реальной изоляции нужен хост Mint/Ubuntu с установленными Bubblewrap и `prlimit`. ## Локальные проверки @@ -17,7 +18,8 @@ python3 -m unittest discover -s tests -v python3 -m compileall -q src tests run.py find static -name '*.js' -print0 | xargs -0 -n1 node --check -bash -n setup.sh +bash -n setup.sh && bash -n setup_termux.sh +python3 nerveforge install --plan # установщик по-прежнему запускается python3 scripts/gen_api_doc.py --check # docs/API.md актуален python3 scripts/bump_version.py --check # версия одна на все артефакты python3 scripts/check_docs.py # EN/RU не разъехались diff --git a/docs/ru/README.md b/docs/ru/README.md index 9f50a2f..4aa37f9 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.6.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.7.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](../../assets/nerveforge-lockup.png) @@ -45,45 +45,52 @@ ## 🚀 Руководство пользователя: Как пользоваться приёмником -### Шаг 1: Запуск приёмника на устройстве +### Шаг 1: Установка и запуск -Выберите вашу платформу: +Одна команда на любой платформе. Установщик — это программа на Python, поэтому +одни и те же вопросы и один и тот же отчёт на Linux, macOS, Windows и Termux: -#### 🐧 1. На Linux (Ubuntu / Linux Mint / Debian): ```bash -# Клонирование и запуск в 1 команду: git clone https://github.com/foursecondfivefour/NerveForge.git cd NerveForge -bash setup.sh +./nerveforge install # задаст несколько вопросов и запустит приёмник ``` -#### 🪟 2. На Windows 10 / 11 (PowerShell): -```powershell -git clone https://github.com/foursecondfivefour/NerveForge.git -cd NerveForge -Set-ExecutionPolicy -Scope Process Bypass -.\setup_windows.ps1 +На Windows — `.\nerveforge install` (или `python nerveforge install`). Если файл +не запускается как программа: `python3 nerveforge install`. -# Дополнительные ключи -.\setup_windows.ps1 -InstallTunnel # предложить cloudflared/Tailscale из winget -.\setup_windows.ps1 -TunnelMode cloudflared # auto (по умолчанию), cloudflared, tailscale, none -.\setup_windows.ps1 -NoStart # только подготовить окружение -``` +Установщик проверяет Python, спрашивает туннель, предлагает скачать +`cloudflared`, спрашивает папку, в которой разрешено работать агенту, и +запускает приёмник. Каждый шаг печатает, что найдено или почему остановились, +и ничего не меняется на машине без вашего `Y`. -Установщик проверяет Python, выбирает туннель, спрашивает рабочую папку и -запускает приёмник. Каждый шаг сообщает, что найдено или почему остановились; -ничего не ставится без явного `Y`. Токен и кодовая фраза полного доступа -печатаются в баннере при старте. Если панель пишет **unauthorized** — нет -токена: скопируйте его из баннера или вставьте на экране «Настройки». - -#### 📱 3. На Android (в приложении Termux): ```bash -git clone https://github.com/foursecondfivefour/NerveForge.git -cd NerveForge -bash setup_termux.sh +./nerveforge install --plan # что изменилось бы, и на этом остановиться +./nerveforge install --yes # принять значения по умолчанию, без вопросов +./nerveforge install --tunnel none # только локально, без публичного адреса +./nerveforge install --json --plan # тот же план для другой программы ``` -*(Или универсально на любой ОС с установленным Python 3.10+: `python3 run.py`)* +| Вопрос | По умолчанию | +|---|---| +| Туннель | `auto`: `cloudflared`, если он есть, иначе Tailscale, иначе локально | +| Скачать `cloudflared` в папку данных | спрашивает, никогда не молча | +| Рабочая папка для агента | `~/Projects` | +| Ярлык на рабочем столе / в меню | да на десктопе, пропускается на сервере и в Termux | +| Команда `nerveforge` в `PATH` | нет — предлагается, но не навязывается | +| Запустить приёмник после установки | да | + +Старые точки входа работают и теперь передают управление тому же установщику, +так что старый README или сохранённый ярлык ничего не сломают: `bash setup.sh`, +`bash setup_termux.sh`, `.\setup_windows.ps1`, `python3 run.py`. + +Убрать то, что создал установщик — ярлык, лаунчер, скачанный `cloudflared` — +можно командой `./nerveforge uninstall`. Токен, настройки, скиллы и журнал +аудита остаются: они ваши, а не установщика. + +Токен и кодовая фраза полного доступа печатаются в баннере при старте. Если +панель пишет **unauthorized** — нет токена: скопируйте его из баннера или +вставьте на экране «Настройки». ### Нет cloudflared? Панель скачает его сама @@ -277,10 +284,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1834 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1894 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1834 unit-тестов +# Запуск 1894 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -338,6 +345,7 @@ nerveforge/ │ ├── config_manager.py # Мониторинг конфигураций systemd/autostart │ ├── paths.py # Разрешение путей данных и конфигураций │ ├── platform_support.py # ОС и реестр оболочек (bash/zsh/sh/fish/PowerShell/CMD/WSL) +│ ├── installer/ # `nerveforge install`: десять шагов, меню и отчёт │ ├── tunnel/ # CLI, менеджер и провайдеры туннелей (cloudflared/tailscale) │ │ ├── cli.py # запуск приёмника, сигналы, коды возврата │ │ ├── manager.py # ровно один активный провайдер + tunnel.json @@ -347,12 +355,13 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1834 тестов) +├── tests/ # Набор unit-тестов (1894 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 -├── run.py # Точка входа для запуска на месте -├── setup.sh # Установщик для Linux Mint / Ubuntu -├── setup_windows.ps1 # Установщик для Windows 10/11 -├── setup_termux.sh # Установщик для Android (Termux) +├── nerveforge # ./nerveforge — запуск или `install` по шагам +├── run.py # Синоним ./nerveforge (старые ярлыки работают) +├── setup.sh # Передаёт управление: находит Python и запускает `nerveforge install` +├── setup_windows.ps1 # То же для Windows PowerShell +├── setup_termux.sh # То же для Android (Termux) ├── AGENTS.md # Инструкция для ИИ-агентов ├── CHANGELOG.md # История версий ├── SECURITY.md # Политика безопасности diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index ad753da..ee49d00 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.6.0 +# Security policy — NerveForge 8.7.0 [English](../../SECURITY.md) · **Русский** diff --git a/nerveforge b/nerveforge new file mode 100755 index 0000000..9760050 --- /dev/null +++ b/nerveforge @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Run NerveForge, or install it, from a checkout — with no arguments to remember. + + ./nerveforge start the bridge (what most people want) + ./nerveforge install the step-by-step installer + ./nerveforge install --plan + ./nerveforge --help + +This file is deliberately small and has no dependencies beyond the standard +library: it is what an operator runs before anything is installed, so it cannot +import the project until it has found it. +""" +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT / "src")) + + +def main() -> int: + argv = [str(arg) for arg in sys.argv[1:]] + if argv and argv[0] == "install": + from nerveforge.installer.cli import main as install_main + + return install_main(argv[1:]) + if argv and argv[0] == "uninstall": + from nerveforge.installer.cli import uninstall_main + + return uninstall_main(argv[1:]) + if argv and argv[0] in ("-h", "--help", "help"): + print(__doc__.strip()) + return 0 + + # Anything else is the bridge's own command line. + from nerveforge.tunnel import main as run_main + + return run_main(argv) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/run.py b/run.py old mode 100644 new mode 100755 index 3ee1257..5659347 --- a/run.py +++ b/run.py @@ -1,5 +1,10 @@ #!/usr/bin/env python3 -"""Project-root entry point; makes the src-layout package runnable in place.""" +"""Start NerveForge from a checkout. Kept for older instructions and shortcuts. + +`./nerveforge` is the same thing with the installer one word away. This file +exists because a shortcut, a README from an earlier version or a cron job may +still name `run.py`, and a rename should not break them. +""" from __future__ import annotations import runpy @@ -9,11 +14,12 @@ ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT / "src")) -# Console output is Cyrillic; legacy code pages cannot encode it. try: from nerveforge.core.console import configure_console except ImportError: # pragma: no cover - only if the tree is incomplete pass else: configure_console() -runpy.run_module("nerveforge", run_name="__main__") + +if __name__ == "__main__": + runpy.run_module("nerveforge", run_name="__main__") diff --git a/scripts/bump_version.py b/scripts/bump_version.py index 9ef5036..fc199b2 100644 --- a/scripts/bump_version.py +++ b/scripts/bump_version.py @@ -8,7 +8,8 @@ Artifacts that carry the version: * ``src/nerveforge/_version.py`` — single source of truth (read at runtime); -* ``VERSION`` — read by ``setup_termux.sh``; +* ``VERSION`` — the release marker the updater compares against, and the + version the installer prints; * ``pyproject.toml`` — dynamic version, no literal to bump; * the ``Server`` header (built from ``__version__``), no literal; * the README and ``SECURITY.md`` headings — in English and in the Russian diff --git a/setup.sh b/setup.sh old mode 100644 new mode 100755 index 6f64d1b..bf01955 --- a/setup.sh +++ b/setup.sh @@ -1,55 +1,32 @@ #!/usr/bin/env bash -# One-pass installer for Linux Mint / Ubuntu: deps + launcher + first start. +# Kept so that older instructions keep working. The installer is Python now: +# one program for Linux, macOS, Windows and Termux, with the same steps and the +# same explanations. This script only finds a Python 3.10+ and hands over. set -euo pipefail ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" if [[ "${EUID}" -eq 0 ]]; then - echo "Запустите обычным пользователем, без sudo: bash setup.sh" >&2 + echo "Run this as your normal user, not with sudo: bash setup.sh" >&2 + echo "(The installer asks for elevated rights itself when a step needs them.)" >&2 exit 2 fi -if ! command -v apt-get >/dev/null 2>&1 || ! command -v dpkg >/dev/null 2>&1; then - echo "Этот простой установщик поддерживает Linux Mint и Ubuntu (APT)." >&2 - echo "На другой системе установите Python 3.10+ и (опционально) tailscale вручную." >&2 - exit 2 -fi - -# Install only what's missing. System packages are installed by APT after sudo confirmation. -packages=() -command -v python3 >/dev/null 2>&1 || packages+=(python3) -command -v curl >/dev/null 2>&1 || packages+=(curl) -command -v prlimit >/dev/null 2>&1 || packages+=(util-linux) - -if ((${#packages[@]})); then - echo "Установщик добавит недостающие системные пакеты: ${packages[*]}" - echo "Сейчас появится обычный запрос пароля администратора от APT." - sudo -v - sudo apt-get update - sudo apt-get install -y "${packages[@]}" -fi - -python3 - <<'PY' -import sys -if sys.version_info < (3, 10): - raise SystemExit("Нужен Python 3.10 или новее. Обновите Linux Mint/Ubuntu и повторите bash setup.sh") -print(f"Python {sys.version.split()[0]} готов") -PY -# Cloudflare Quick Tunnel is primary; Tailscale is fallback. -if command -v cloudflared >/dev/null 2>&1; then - echo "Cloudflared найден: будет использован Cloudflare Quick Tunnel (основной режим)." -elif command -v tailscale >/dev/null 2>&1; then - echo "Cloudflared не найден; доступен резервный режим Tailscale." -else - echo "Клиент туннеля не найден: приложение запустится в локальном режиме." - echo "Для публичного доступа установите cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/" +PYTHON="" +for candidate in python3.13 python3.12 python3.11 python3.10 python3; do + if command -v "$candidate" >/dev/null 2>&1 && + "$candidate" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; then + PYTHON="$candidate" + break + fi +done + +if [[ -z "$PYTHON" ]]; then + echo "Python 3.10 or newer is required and was not found." >&2 + echo "Install it (apt install python3, brew install python, pkg install python)" >&2 + echo "and run this script again." >&2 + exit 2 fi -echo "Bubblewrap (песочница проектной зоны): $(command -v bwrap || echo 'не найден — запуск команд в YOLO будет закрыт, полный доступ работает без него')" - -python3 "$ROOT/scripts/install_desktop_launcher.py" -echo -echo "Установка готова. Открываю NerveForge; окно терминала нужно оставить открытым." -echo "Закрыть приложение безопасно: Ctrl+C в этом окне." -echo -exec python3 "$ROOT/run.py" +echo "Using $("$PYTHON" -c 'import sys; print(sys.executable)')" +exec "$PYTHON" "$ROOT/nerveforge" install "$@" diff --git a/setup_termux.sh b/setup_termux.sh old mode 100644 new mode 100755 index 3e21b07..d0757b7 --- a/setup_termux.sh +++ b/setup_termux.sh @@ -1,26 +1,23 @@ #!/usr/bin/env bash -# One-pass installer for Termux (Android): Python + Cloudflared / Tailscale + start. +# Kept so that older instructions keep working. The real installer is Python: +# `./nerveforge install`. This script only makes sure the two things Termux does +# not ship are present, then hands over. set -euo pipefail ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -VERSION="$(cat "$ROOT/VERSION" 2>/dev/null || echo 7.0.7)" -echo "==================================================" -echo " NerveForge $VERSION — Установка в Termux (Android)" -echo "==================================================" +if ! command -v pkg >/dev/null 2>&1; then + echo "This script is for Termux on Android. Elsewhere use: ./nerveforge install" >&2 + exit 2 +fi -pkg update -y || true -pkg install -y python git curl || true +pkg install -y python >/dev/null || true -if ! command -v cloudflared >/dev/null 2>&1; then - echo "Установка cloudflared..." - pkg install -y cloudflared 2>/dev/null || echo "cloudflared не найден в стандартных репозиториях; можно установить через tur-repo" +if ! command -v python3 >/dev/null 2>&1; then + echo "Python could not be installed. Run: pkg update && pkg install python" >&2 + exit 2 fi termux-setup-storage 2>/dev/null || true -echo -echo "NerveForge готов к запуску в Termux!" -echo "Запускаю сервер моста..." -echo -exec python3 "$ROOT/run.py" +exec python3 "$ROOT/nerveforge" install "$@" diff --git a/setup_windows.ps1 b/setup_windows.ps1 index fc22579..89c03a9 100644 --- a/setup_windows.ps1 +++ b/setup_windows.ps1 @@ -1,297 +1,49 @@ -#Requires -Version 5.1 -<# -.SYNOPSIS - Запуск NerveForge на Windows: проверка Python, выбор туннеля, рабочая папка. - -.DESCRIPTION - Скрипт ничего не делает молча. Каждый шаг либо сообщает, что нашёл, либо - спрашивает подтверждение, либо называет причину, по которой дальше нельзя. - - Установка программ — только по явному согласию: без -InstallMissing скрипт - ничего не ставит, а показывает список пакетов и ждёт ответа. - -.PARAMETER InstallMissing - Разрешить установку Python через winget, если его нет. - -.PARAMETER InstallTunnel - Разрешить установку клиента туннеля через winget, если не найден ни один. - Без этого флага скрипт предложит варианты и остановится. - -.PARAMETER TunnelMode - auto (по умолчанию), cloudflared, tailscale или none. - -.PARAMETER NoStart - Только подготовить окружение, не запускать приёмник. - -.EXAMPLE - .\setup_windows.ps1 - Обычный первый запуск: проверки, вопросы, запуск. - -.EXAMPLE - .\setup_windows.ps1 -InstallTunnel -TunnelMode cloudflared - Согласие на установку cloudflared и запуск через Cloudflare Quick Tunnel. -#> +# setup_windows.ps1 — kept so that older instructions keep working. +# +# The installer is Python now, and it is the same program on every system: +# `.\nerveforge install`. This script finds a Python 3.10+ and hands over; it +# installs nothing itself, so there is one place where the steps live and one +# place to fix a step that breaks. +# +# New parameters do not belong here. Add them to `nerveforge install` instead, +# where Linux, macOS and Termux get them too. +# +# Usage: +# .\setup_windows.ps1 interactive, the same questions +# .\setup_windows.ps1 --plan show what would change +# .\setup_windows.ps1 --tunnel none pass any installer flag through [CmdletBinding()] param( - [switch]$InstallMissing, - [switch]$InstallTunnel, - [ValidateSet('auto', 'cloudflared', 'tailscale', 'none')] - [string]$TunnelMode = 'auto', - [switch]$NoStart + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$InstallerArgs ) $ErrorActionPreference = 'Stop' $Root = Split-Path -Parent $MyInvocation.MyCommand.Path -$script:Warnings = 0 -$script:ExitCode = 0 - -# ---------------------------------------------------------------- вывод -function Write-Step([string]$Text) { - Write-Host '' - Write-Host "== $Text" -ForegroundColor Cyan -} -function Write-Ok([string]$Text) { Write-Host " [ok] $Text" -ForegroundColor Green } -function Write-Note([string]$Text) { Write-Host " $Text" } -function Write-Problem([string]$Text) { - Write-Host " [!] $Text" -ForegroundColor Yellow - $script:Warnings++ -} -function Write-Fail([string]$Text) { Write-Host " [x] $Text" -ForegroundColor Red } - -function Read-YesNo([string]$Question, [bool]$Default = $true) { - $hint = if ($Default) { '[Y/n]' } else { '[y/N]' } - $answer = Read-Host "$Question $hint" - if (-not $answer) { return $Default } - return $answer -in @('Y', 'y', 'YES', 'yes', 'Д', 'д', 'ДА', 'да') -} - -function Confirm-Phrase([string]$Prompt) { - $answer = Read-Host $Prompt - return $answer -ceq 'RUN AS ADMIN' -} - -# ------------------------------------------------------------ окружение -function Test-IsAdmin { - $identity = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = [Security.Principal.WindowsPrincipal]::new($identity) - return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -} - -function Get-PythonLauncher { - <# Возвращает @{ Exe; Prefix; Version } или $null. #> - $candidates = @() - $python = Get-Command python.exe -ErrorAction SilentlyContinue - if ($python) { $candidates += @{ Exe = $python.Source; Prefix = @() } } - $py = Get-Command py.exe -ErrorAction SilentlyContinue - if ($py) { $candidates += @{ Exe = $py.Source; Prefix = @('-3') } } - - foreach ($candidate in $candidates) { - # chr(46) вместо '.' — кавычки вокруг аргумента ломаются в native-вызовах. - $version = & $candidate.Exe @($candidate.Prefix) -c 'import sys; print(str(sys.version_info.major)+chr(46)+str(sys.version_info.minor))' 2>$null - if ($LASTEXITCODE -ne 0 -or -not $version) { continue } - $parts = $version.Trim().Split('.') - if ([int]$parts[0] -lt 3) { continue } - if ([int]$parts[0] -eq 3 -and [int]$parts[1] -lt 10) { continue } - return @{ Exe = $candidate.Exe; Prefix = $candidate.Prefix; Version = $version.Trim() } - } - return $null -} - -function Get-TunnelBinary([string]$Name) { - return Get-Command "$Name.exe" -ErrorAction SilentlyContinue -} - -function Install-WingetPackage([string]$Id, [string]$What) { - $winget = Get-Command winget.exe -ErrorAction SilentlyContinue - if (-not $winget) { - Write-Fail "winget.exe не найден — установите $What вручную." - return $false - } - $answer = Read-Host "Установить $What из winget (пакет $Id)? Введите Y для подтверждения" - if ($answer -notin @('Y', 'y', 'YES', 'yes', 'Д', 'д', 'ДА', 'да')) { - Write-Note 'Установка отменена; скрипт продолжит без неё.' - return $false - } - & $winget.Source install --id $Id --exact --scope user ` - --accept-package-agreements --accept-source-agreements - if ($LASTEXITCODE -ne 0) { - Write-Fail "winget завершился с кодом $LASTEXITCODE при установке $What." - return $false - } - Write-Ok "$What установлен." - return $true -} - -# --------------------------------------------------------------- шаги -function Step-AdminNotice { - if (Test-IsAdmin) { - Write-Step 'Права администратора' - Write-Warning 'Передатчик и удалённые команды будут работать с правами администратора: команды через туннель смогут менять системные настройки и файлы других пользователей.' - if (-not (Confirm-Phrase 'Для продолжения введите RUN AS ADMIN')) { - throw 'Запуск с правами администратора отменён.' - } - } -} -function Step-Python { - Write-Step 'Python' - $launcher = Get-PythonLauncher - if ($launcher) { - Write-Ok "Python $($launcher.Version) — $($launcher.Exe)" - return $launcher +function Find-Python { + $candidates = @('python', 'python3', 'py') + foreach ($name in $candidates) { + $exe = Get-Command $name -ErrorAction SilentlyContinue + if (-not $exe) { continue } + $probe = @( + '-c', + 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' + ) + & $exe.Source @probe 2>$null + if ($LASTEXITCODE -eq 0) { return $exe.Source } } - - Write-Problem 'Python 3.10+ не найден.' - if (-not $InstallMissing) { - Write-Note 'Варианты:' - Write-Note ' 1) Установить Python 3.12 с python.org и запустить скрипт снова.' - Write-Note ' 2) Запустить с -InstallMissing — скрипт предложит winget-пакет.' - $script:ExitCode = 2 - return $null - } - if (Install-WingetPackage 'Python.Python.3.12' 'Python 3.12') { - Write-Note 'Закройте и откройте PowerShell заново, затем повторите setup_windows.ps1.' - $script:ExitCode = 0 - return $null - } - $script:ExitCode = 2 return $null } -function Step-Tunnel { - Write-Step 'Туннель' - $cloudflared = Get-TunnelBinary 'cloudflared' - $tailscale = Get-TunnelBinary 'tailscale' - - if ($cloudflared) { Write-Ok "cloudflared: $($cloudflared.Source)" } - if ($tailscale) { Write-Ok "tailscale: $($tailscale.Source)" } - - switch ($TunnelMode) { - 'none' { - Write-Note 'Выбран локальный режим: публичного адреса не будет.' - return 'none' - } - 'cloudflared' { - if ($cloudflared) { return 'cloudflared' } - Write-Problem 'cloudflared не установлен.' - if ($InstallTunnel -and (Install-WingetPackage 'Cloudflare.cloudflared' 'cloudflared')) { - return 'cloudflared' - } - Write-Note 'Установите cloudflared вручную или запустите с -InstallTunnel.' - $script:ExitCode = 2 - return $null - } - 'tailscale' { - if ($tailscale) { return 'tailscale' } - Write-Problem 'tailscale не установлен.' - if ($InstallTunnel -and (Install-WingetPackage 'Tailscale.Tailscale' 'Tailscale')) { - return 'tailscale' - } - Write-Note 'Установите Tailscale вручную или запустите с -InstallTunnel.' - $script:ExitCode = 2 - return $null - } - } - - if ($cloudflared) { - Write-Note 'Будет использован Cloudflare Quick Tunnel: аккаунт не нужен, адрес меняется при каждом запуске.' - return 'cloudflared' - } - if ($tailscale) { - Write-Note 'cloudflared не найден — будет использован Tailscale Funnel (нужен вход в Tailscale).' - return 'tailscale' - } - - Write-Problem 'Ни cloudflared, ни tailscale не найдены: панель будет доступна только локально.' - Write-Note 'Это рабочий режим — команды и файлы доступны с этой машины.' - Write-Note 'Для публичного доступа: -InstallTunnel (winget) или cloudflare.com/cloudflare-one/connections/connect-networks/downloads/' - if ($InstallTunnel) { - $choice = 'Cloudflare.cloudflared' - if (Read-YesNo 'Установить Tailscale вместо cloudflared?' $false) { $choice = 'Tailscale.Tailscale' } - $what = if ($choice -eq 'Cloudflare.cloudflared') { 'cloudflared' } else { 'Tailscale' } - if (Install-WingetPackage $choice $what) { return 'auto' } - } - return 'none' -} - -function Step-Workspace { - Write-Step 'Рабочая папка' - $current = [Environment]::GetEnvironmentVariable('NERVEFORGE_WORKSPACE', 'User') - if (-not $current) { - $current = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'NerveForgeProjects' - } - Write-Note "Сейчас: $current" - Write-Note 'Агент работает только внутри этой папки. Укажите свой проект, если нужно.' - - $input = Read-Host 'Путь (Enter — оставить как есть)' - if ($input.Trim()) { - $current = [Environment]::ExpandEnvironmentVariables($input.Trim().Trim('"')) - } - if (-not [IO.Path]::IsPathRooted($current)) { - Write-Fail "Нужен абсолютный путь, получено: $current" - $script:ExitCode = 2 - return $null - } - if (-not (Test-Path -LiteralPath $current -PathType Container)) { - if (-not (Read-YesNo "Папки нет. Создать '$current'?" $true)) { - Write-Fail 'Рабочая папка не выбрана; запуск остановлен.' - $script:ExitCode = 2 - return $null - } - New-Item -ItemType Directory -Path $current -Force | Out-Null - } - $resolved = (Resolve-Path -LiteralPath $current).Path - [Environment]::SetEnvironmentVariable('NERVEFORGE_WORKSPACE', $resolved, 'User') - $env:NERVEFORGE_WORKSPACE = $resolved - Write-Ok "Рабочая папка: $resolved" - return $resolved -} - -function Step-Summary([string]$PythonVersion, [string]$Tunnel, [string]$Workspace) { - Write-Step 'Итог' - Write-Note "NerveForge: $Root" - Write-Note "Python: $PythonVersion" - Write-Note "Туннель: $Tunnel" - Write-Note "Рабочая папка: $Workspace" - Write-Note 'Токен и адрес панели появятся в баннере после запуска. Тем же токеном' - Write-Note 'вводится кодовая фраза полного доступа — она печатается в баннере.' +$Python = Find-Python +if (-not $Python) { + Write-Host "Python 3.10 or newer is required and was not found." -ForegroundColor Red + Write-Host "Install it from https://www.python.org/downloads/ (tick 'Add to PATH')" + Write-Host "or from the Microsoft Store, then run this script again." + exit 2 } -# ----------------------------------------------------------------- main -try { - Step-AdminNotice - - $python = Step-Python - if (-not $python) { exit $script:ExitCode } - - $tunnel = Step-Tunnel - if ($null -eq $tunnel) { exit $script:ExitCode } - - $workspace = Step-Workspace - if (-not $workspace) { exit $script:ExitCode } - - Step-Summary $python.Version $tunnel $workspace - - if ($NoStart) { - Write-Note 'Флаг -NoStart: окружение подготовлено, запуск пропущен.' - exit 0 - } - if (-not (Read-YesNo 'Запустить приёмник и туннель сейчас?' $true)) { - Write-Note 'Запуск пропущен. Повторный запуск: .\setup_windows.ps1' - exit 0 - } - - $runArgs = @((Join-Path $Root 'run.py')) - if ($TunnelMode -ne 'auto') { $runArgs += @('--tunnel', $TunnelMode) } - Push-Location $Root - try { - & $python.Exe @($python.Prefix) @runArgs - } - finally { - Pop-Location - } -} -catch { - Write-Fail $_.Exception.Message - exit 1 -} +Write-Host "Using $Python" +& $Python (Join-Path $Root 'nerveforge') install @InstallerArgs +exit $LASTEXITCODE diff --git a/src/nerveforge/_version.py b/src/nerveforge/_version.py index 2383f1e..045c199 100644 --- a/src/nerveforge/_version.py +++ b/src/nerveforge/_version.py @@ -1,3 +1,3 @@ """Single source of truth for the NerveForge version.""" -__version__ = "8.6.0" +__version__ = "8.7.0" diff --git a/src/nerveforge/installer/__init__.py b/src/nerveforge/installer/__init__.py new file mode 100644 index 0000000..4c9d3cf --- /dev/null +++ b/src/nerveforge/installer/__init__.py @@ -0,0 +1,34 @@ +"""NerveForge's installer: a sequence of small, reversible, explainable steps. + +The old installers were three shell scripts, one per platform, and the only way +to learn what they would do was to read them. This package replaces them with +one Python program that runs everywhere Python runs (the bridge already needs +it) and that can answer three questions before it touches anything: + +* **what will happen** — `nerveforge install --plan` prints every step, what it + found, and what it would change; +* **what happened** — every step is recorded with the reason it was skipped, + succeeded or failed; +* **how to undo it** — `nerveforge install --uninstall` removes what the + installer created, and nothing else. + +Layout, by responsibility: + +``steps`` + The step model itself: one dataclass, three outcomes, and the `Report` that + the CLI and the tests both read. +``detect`` + The environment probes, each returning a fact and never raising. +``actions`` + The steps: system checks, tunnel choice, workspace, launcher, first start. +``menu`` + The interactive prompts, and the rule that nothing is installed without a + yes. +``cli`` + Argument parsing and the two entry points (`main`, `uninstall_main`). + +Two things this package deliberately does not do: it never edits `PATH`, and it +never installs something the operator did not confirm. Anything it downloads +goes into the user data directory, the same place the panel already puts +`cloudflared`. +""" diff --git a/src/nerveforge/installer/actions.py b/src/nerveforge/installer/actions.py new file mode 100644 index 0000000..fd9cbb7 --- /dev/null +++ b/src/nerveforge/installer/actions.py @@ -0,0 +1,359 @@ +"""The steps themselves: what the installer actually does, one function each. + +Each step takes the `Step` it is filling in and returns it, so the screen shows +the result whether the step succeeded, skipped or failed. None of them prints to +stdout on its own — the caller renders the report — which is what lets the same +code serve `--plan`, the interactive run, and a JSON answer to another program. + +The order matters and is the order of `STEPS`. It is a dependency order: Python +before the tunnel, the tunnel before the first start, the workspace before the +shortcut that opens it. +""" +from __future__ import annotations + +import os +import shutil +import stat +import subprocess +import sys +from pathlib import Path + +from . import detect +from .steps import Outcome, Step, StepContext + + +#: Where the panel puts a downloaded cloudflared, and the installer too. One +#: directory, so `--uninstall` and the panel clean up the same file. +def bin_dir() -> Path: + from .. import paths + + return paths.data_dir() / "bin" + + +# -- 1. python --------------------------------------------------------------- +def check_python(ctx: StepContext, step: Step) -> Step: + """The bridge needs 3.10, and running on the wrong one fails much later.""" + info = ctx.python() + if info.supported: + return step.done(f"Python {info.text} at {info.executable}") + return step.fail( + f"Python {info.text} is too old; NerveForge needs 3.10 or newer", + remedy="Install Python 3.10+ (python.org, your package manager, or `pkg install " + "python` in Termux) and run the installer again.") + + +# -- 2. elevation ------------------------------------------------------------ +def check_elevation(ctx: StepContext, step: Step) -> Step: + """Root changes what a mistake costs, so it is said once, up front.""" + if not detect.admin(): + return step.done("running as a normal user") + if ctx.assume_yes: + return step.done("running as administrator; commands through the bridge will " + "have the same rights") + return step.skip( + "running with administrator rights: anything reachable through the bridge " + "can change system settings and other users' files", fatal=True) + + +# -- 3. tunnel --------------------------------------------------------------- +def choose_tunnel(ctx: StepContext, step: Step) -> Step: + """Pick the tunnel, and say what the choice costs. + + Nothing is installed here even when the answer is yes: `install_tunnel` is + the next step, so the report can show "chosen" and "installed" separately. + That distinction is the whole reason a failed download does not look like a + failed first start. + """ + asked = str(ctx.answer("tunnel", "auto")) + found = detect.tunnel_clients() + + if asked == "none": + return step.done("local mode: the panel is reachable on this machine only") + + choice = asked + if choice == "auto": + choice = ("cloudflared" if found["cloudflared"] + else "tailscale" if found["tailscale"] else "none") + if choice == "cloudflared" and not found["cloudflared"]: + if not ctx.answer("install_tunnel"): + return step.fail( + "cloudflared is not installed and downloading it was declined", + remedy="Re-run and accept the download, install it from " + "cloudflare.com, or pass --tunnel none for local-only use.") + return step.done("cloudflared will be downloaded next") + if choice == "tailscale" and not found["tailscale"]: + return step.fail( + "tailscale is not installed", + remedy="Install Tailscale (tailscale.com/download), or pass --tunnel none.") + if choice == "none": + return step.done("local mode: neither tunnel client is installed, so there is " + "no public address until one is") + where = found.get(choice) + return step.done(f"{choice} at {where}" if where else f"{choice} selected") + + +# -- 4. install the tunnel client ------------------------------------------- +def install_tunnel(ctx: StepContext, step: Step) -> Step: + """Download cloudflared into the data directory when that is the choice.""" + chosen = ctx.answer("tunnel", "auto") + found = detect.tunnel_clients() + if chosen == "none" or (chosen == "auto" and not found["cloudflared"]): + return step.skip("no download needed") + if found["cloudflared"] and chosen in ("auto", "cloudflared"): + return step.skip(f"already installed at {found['cloudflared']}") + if chosen != "cloudflared": + return step.skip(f"{chosen} is a system package, not a download") + if not ctx.answer("install_tunnel"): + return step.skip("download declined") + if ctx.dry_run: + return step.done(f"would download cloudflared into {bin_dir()}") + from ..tunnel import install as tunnel_install + + try: + release = tunnel_install.resolve_release() + report = tunnel_install.install(release=release) + except tunnel_install.InstallError as exc: + # Not fatal: a download is what this step was for, and the bridge runs + # locally without it. Stopping the whole install over a blocked mirror + # would hide a working receiver behind a network problem. + return step.fail(f"cloudflared could not be downloaded: {exc}", fatal=False, + remedy="The bridge still works locally. Press Download " + "cloudflared in the panel later, or install it by hand.") + return step.done(f"cloudflared {report.get('tag', release.tag)} at {report['path']} " + f"(SHA-256 verified)") + + +# -- 5. workspace ------------------------------------------------------------ +def prepare_workspace(ctx: StepContext, step: Step) -> Step: + """Make sure the folder the agent is confined to exists and is writable.""" + chosen = ctx.answer("workspace") + if not chosen: + from .. import paths + + chosen = paths.workspace_dir() + target = Path(chosen).expanduser() + if not target.is_absolute(): + return step.fail(f"the workspace must be an absolute path, got {target}", + remedy="Pass an absolute path, e.g. --workspace ~/Projects/." + " The shell expands ~, the installer does not guess.") + if ctx.dry_run: + return step.done(f"would use {target}") + if detect.writable_directory(target): + return step.done(str(target)) + return step.fail(f"{target} exists but cannot be written to", + remedy="Pick another folder with --workspace, or fix its " + "permissions. The agent runs commands inside it.") + + +# -- 6. working folders next to the app -------------------------------------- +def prepare_state(ctx: StepContext, step: Step) -> Step: + """Create the config and data directories the first start would create anyway. + + Doing it here means the first start cannot fail on a permission problem that + the installer could have found while the operator was still watching. + """ + from .. import paths + + targets = [paths.config_dir(), paths.data_dir()] + if ctx.dry_run: + return step.done("would create " + ", ".join(str(path) for path in targets)) + for target in targets: + if not detect.writable_directory(target): + return step.fail(f"{target} is not writable", + remedy="Check the permissions of your home directory.") + return step.done(", ".join(str(path) for path in targets)) + + +# -- 7. shortcut ------------------------------------------------------------- +def install_shortcut(ctx: StepContext, step: Step) -> Step: + """A menu entry on a desktop, a note on a server, nothing on a phone.""" + wanted = ctx.answer("shortcut") + if wanted is False: + return step.skip("declined") + if not detect.desktop_environment(): + if detect.is_termux(): + return step.skip("Termux has no application menu; run ./nerveforge or " + "the widget launcher instead") + return step.skip("no desktop session detected; start it with ./nerveforge") + if wanted is None and not ctx.assume_yes and not ctx.answer("interactive"): + # In a non-interactive run, a shortcut is a change to somebody's desktop + # that they did not ask for; the default is to leave it alone. + return step.skip("not requested (pass --shortcut on a server with a desktop)") + + from .apps import write_shortcut + + try: + files = write_shortcut(ctx.root, ctx.python().executable, dry_run=ctx.dry_run) + except OSError as exc: + return step.fail(f"could not write the shortcut: {exc}", fatal=False) + if ctx.dry_run: + return step.done("would write " + ", ".join(str(file) for file in files)) + return step.done(", ".join(str(file) for file in files)) + + +# -- 8. command on PATH ------------------------------------------------------ +def install_command(ctx: StepContext, step: Step) -> Step: + """Put a `nerveforge` command somewhere the shell already looks. + + Only a directory that is already on `PATH` and belongs to this user is used: + the installer never edits a shell profile, because a broken profile is a + machine the operator cannot log into. + """ + if not ctx.answer("command"): + return step.skip("not requested (pass --command to add it)") + from .apps import command_targets, write_launcher + + target = command_targets() + if target is None: + return step.skip("no per-user directory on PATH to put it in; run ./nerveforge", + fatal=False) + if ctx.dry_run: + return step.done(f"would write {target}") + try: + write_launcher(target, ctx.root, ctx.python().executable) + except OSError as exc: + return step.fail(f"could not write {target}: {exc}", fatal=False) + return step.done(f"{target} (already on PATH)") + + +# -- 9. self-check ----------------------------------------------------------- +def self_check(ctx: StepContext, step: Step) -> Step: + """Import the bridge and read its version, without starting a listener. + + A first start that fails because the tree is incomplete should fail here, + with a sentence, rather than after the tunnel has been brought up. + """ + try: + from .._version import __version__ + from ..http.app import build_routes_only + except Exception as exc: # noqa: BLE001 — importing a tree can fail any way + return step.fail(f"the program cannot be imported: {exc}", + remedy="Re-clone the repository, or check that ./nerveforge " + "was copied with its src/ directory.") + try: + routes = len(build_routes_only().routes) + except Exception as exc: # noqa: BLE001 + return step.fail(f"the HTTP layer did not load: {exc}") + return step.done(f"NerveForge {__version__}, {routes} routes, " + f"{ctx.python().text} at {ctx.python().executable}") + + +# -- 10. first start --------------------------------------------------------- +def start(ctx: StepContext, step: Step) -> Step: + """Start the bridge and keep this process attached, like every installer does.""" + if ctx.answer("start") is False: + return step.skip("declined; start it later with ./nerveforge") + if ctx.dry_run: + return step.done("would start the bridge and print the address and token") + from .apps import start_bridge + + return start_bridge(ctx, step) + + +#: The steps in dependency order, with the flag that runs only them. +STEPS = ( + ("python", check_python), + ("elevation", check_elevation), + ("tunnel", choose_tunnel), + ("tunnel-install", install_tunnel), + ("state", prepare_state), + ("workspace", prepare_workspace), + ("shortcut", install_shortcut), + ("command", install_command), + ("self-check", self_check), + ("start", start), +) + +#: Titles for the screen and for `--plan`. Kept beside the functions so adding a +#: step is one edit, not two. +TITLES = { + "python": "Python version", + "elevation": "Administrator rights", + "tunnel": "Tunnel", + "tunnel-install": "Tunnel download", + "state": "Config and data folders", + "workspace": "Working folder", + "shortcut": "Desktop shortcut", + "command": "`nerveforge` command", + "self-check": "Program check", + "start": "Start the bridge", +} + +#: The steps that change the machine. `--plan` prints them, and only these are +#: undone by `--uninstall`. +CHANGING = frozenset({"tunnel-install", "state", "workspace", "shortcut", "command"}) + + +def run(keys: list[str] | None = None, *, answers: dict | None = None, + assume_yes: bool = False, dry_run: bool = False, root: Path | None = None, + python=None, only: set[str] | None = None): + """Run the steps and return the report. The one entry point for everything. + + `answers` is filled before the run, which is what makes a plan possible: no + step blocks on a question. `only` restricts the run to named steps, which is + how `--uninstall` and the tests use the same machinery. + """ + from .. import paths + from .steps import Report + + answers = dict(answers or {}) + answers.setdefault("interactive", streaming_stdin()) + root = Path(root) if root else Path(__file__).resolve().parents[3] + found_python = detect.find_supported_python(answers.get("python")) + ctx = StepContext(answers=answers, assume_yes=assume_yes, dry_run=dry_run, + root=root, python=lambda: found_python, + platform=sys.platform) + if answers.get("workspace") is None: + answers["workspace"] = str(paths.workspace_dir()) + + report = Report(dry_run=dry_run) + for key, function in STEPS: + if only is not None and key not in only: + continue + if keys and key not in keys: + continue + step = Step(key=key, title=TITLES.get(key, key)) + try: + function(ctx, step) + except Exception as exc: # noqa: BLE001 — a step must not kill the run + step.fail(f"unexpected error: {type(exc).__name__}: {exc}", + remedy="This is a bug: please report it with the line below.") + report.add(step) + if step.outcome is Outcome.FAIL and step.fatal: + break + return report + + +def streaming_stdin() -> bool: + """Whether a person is watching, which decides the defaults for changes.""" + try: + return sys.stdin is not None and sys.stdin.isatty() + except (AttributeError, ValueError): + return False + + +def make_executable(path: Path) -> None: + """chmod +x, without pretending to on a platform that does not have it.""" + if os.name == "nt": + return + mode = path.stat().st_mode + path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def run_command(argv: list[str], *, timeout: int = 600) -> tuple[int, str]: + """Run an external installer step and return (code, tail of its output). + + Used only for a system package manager, where re-implementing the install is + worse than calling it. `argv` is a list, never a shell string. + """ + try: + done = subprocess.run(argv, capture_output=True, text=True, timeout=timeout, # noqa: S603 + check=False) + except (OSError, subprocess.SubprocessError) as exc: + return 1, str(exc) + tail = " / ".join((done.stderr or done.stdout or "").strip().splitlines()[-3:]) + return done.returncode, tail + + +def which(name: str) -> str | None: + return shutil.which(name) diff --git a/src/nerveforge/installer/apps.py b/src/nerveforge/installer/apps.py new file mode 100644 index 0000000..07e6eda --- /dev/null +++ b/src/nerveforge/installer/apps.py @@ -0,0 +1,197 @@ +"""The things the installer leaves behind: a shortcut, a launcher, a first start. + +Kept out of `actions` because these are the parts a test can inspect as files +rather than as process state: a `.desktop` entry is a string, a launcher is a +string, and a start is a call into the tunnel CLI that is replaced in tests. +""" +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +DESKTOP_NAME = "nerveforge.desktop" + + +# -- the launcher script ----------------------------------------------------- +LAUNCHER = """#!/usr/bin/env python3 +\"\"\"Run NerveForge from {root} without activating anything. + +Written by the NerveForge installer. It exists so that `nerveforge` means the +same thing in every shell, including the ones that have never heard of this +project. Delete it, or run `nerveforge install --uninstall`, to remove it. +\"\"\" +import runpy +import sys + +ROOT = {root!r} +sys.path.insert(0, ROOT + "/src") +runpy.run_module("nerveforge", run_name="__main__") +""" + + +def write_launcher(target: Path, root: Path, python: str) -> Path: + """Write an executable Python launcher. + + A Python file rather than a shell script on purpose: the project already + requires Python, the shebang is the only line that differs between systems, + and on Windows the `.py` association is what makes it double-clickable. + """ + target.parent.mkdir(parents=True, exist_ok=True) + text = LAUNCHER.format(root=str(root).replace("\\", "/")) + if target.suffix in (".exe", ".cmd", ".bat"): + # Windows will not run a shebang: wrap the Python file instead. + target.write_text(f"@echo off\r\n\"{python}\" \"%~dp0nerveforge.py\" %*\r\n", + encoding="utf-8") + script = target.with_suffix(".py") + script.write_text(text, encoding="utf-8") + return target + target.write_text(text, encoding="utf-8") + make_executable(target) + return target + + +def make_executable(path: Path) -> None: + if sys.platform.startswith("win"): + return + path.chmod(0o755) + + +def command_targets() -> Path | None: + """The first per-user directory on `PATH` where a `nerveforge` command belongs. + + Only a directory that already exists and belongs to this user is chosen. The + alternative — creating one and editing `~/.bashrc` — is how installers break + shells, and this one will not do it. + """ + import os + + name = "nerveforge.exe" if os.name == "nt" else "nerveforge" + home = Path.home() + on_path = [Path(entry) for entry in os.environ.get("PATH", "").split(os.pathsep) if entry] + for candidate in on_path: + try: + resolved = candidate.expanduser() + if not resolved.is_dir(): + continue + # Refuse system directories: writing there needs root and surprises + # whoever looks after the machine. + if home not in resolved.parents and resolved != home / ".local" / "bin": + continue + if resolved.name in ("bin", "sbin") and home in resolved.parents: + return resolved / name + except OSError: + continue + local_bin = home / ".local" / "bin" + if local_bin in [path.expanduser() for path in on_path] and local_bin.is_dir(): + return local_bin / name + return None + + +# -- the desktop shortcut ---------------------------------------------------- +def desktop_quote(value: str) -> str: + """Quote a value for a `.desktop` Exec line, which is not a shell but is close.""" + escaped = (value.replace("\\", "\\\\").replace('"', '\\"') + .replace("`", "\\`").replace("$", "\\$")) + return f'"{escaped}"' + + +def desktop_entry(root: Path, python: str) -> str: + """The `.desktop` file as a string, so a test can read it without a desktop.""" + icon = root / "assets" / "nerveforge-mark.png" + return ( + "[Desktop Entry]\n" + "Version=1.0\n" + "Type=Application\n" + "Name=NerveForge\n" + "Comment=Start the bridge and its tunnel (Cloudflare or Tailscale)\n" + f"Exec={desktop_quote(python)} {desktop_quote(str(root / 'run.py'))}\n" + f"Path={root}\n" + + (f"Icon={icon}\n" if icon.is_file() else "") + + "Terminal=true\n" + "Categories=Network;Utility;\n" + ) + + +def write_shortcut(root: Path, python: str, *, dry_run: bool = False) -> list[Path]: + """Write the application-menu entry and, if there is one, a desktop icon.""" + applications = Path.home() / ".local" / "share" / "applications" + targets = [applications / DESKTOP_NAME] + xdg = shutil.which("xdg-user-dir") + if xdg: + try: + done = subprocess.run([xdg, "DESKTOP"], capture_output=True, text=True, # noqa: S603 + timeout=10, check=False) + desktop = Path((done.stdout or "").strip()) if done.returncode == 0 else None + if desktop and desktop.is_dir(): + targets.append(desktop / "NerveForge.desktop") + except (OSError, subprocess.SubprocessError): + pass + if dry_run: + return targets + entry = desktop_entry(root, python) + for target in targets: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(entry, encoding="utf-8") + make_executable(target) + return targets + + +def remove_shortcut() -> list[Path]: + """Delete the entries `write_shortcut` creates, and only those.""" + removed = [] + for folder in (Path.home() / ".local" / "share" / "applications", + _xdg_desktop_dir()): + if folder is None: + continue + for name in (DESKTOP_NAME, "NerveForge.desktop"): + target = folder / name + if target.is_file(): + target.unlink() + removed.append(target) + return removed + + +def _xdg_desktop_dir() -> Path | None: + xdg = shutil.which("xdg-user-dir") + if not xdg: + return None + try: + done = subprocess.run([xdg, "DESKTOP"], capture_output=True, text=True, # noqa: S603 + timeout=10, check=False) + except (OSError, subprocess.SubprocessError): + return None + path = Path((done.stdout or "").strip()) if done.returncode == 0 else None + return path if path and path.is_dir() else None + + +# -- the first start --------------------------------------------------------- +def start_bridge(ctx, step): + """Hand over to the tunnel CLI, which owns the banner, the ports and Ctrl+C. + + `run.py` is preferred over importing the CLI so that the started process is + the same one a person gets by typing it: no import-time state from the + installer leaks into the bridge. + """ + root = ctx.root + entry = root / "run.py" + argv = [ctx.python().executable, str(entry if entry.is_file() else root / "src")] + if not entry.is_file(): + argv = [ctx.python().executable, "-m", "nerveforge"] + tunnel = str(ctx.answer("tunnel", "auto")) + if tunnel and tunnel != "auto": + argv += ["--tunnel", tunnel] + port = ctx.answer("port") + if port: + argv += ["--port", str(port)] + ctx.say(f"$ {' '.join(argv)}") + try: + done = subprocess.run(argv, cwd=str(root), check=False) # noqa: S603 + except KeyboardInterrupt: + return step.done("stopped by Ctrl+C") + except OSError as exc: + return step.fail(f"could not start: {exc}", + remedy="Run ./nerveforge directly to see the full error.") + return step.done("stopped" if done.returncode == 0 + else f"exited with code {done.returncode}") diff --git a/src/nerveforge/installer/cli.py b/src/nerveforge/installer/cli.py new file mode 100644 index 0000000..80422b0 --- /dev/null +++ b/src/nerveforge/installer/cli.py @@ -0,0 +1,209 @@ +"""`nerveforge install` — the command, the flags, and the uninstall. + +Flags exist for the cases a question cannot serve: a headless server, a first +boot script, and the operator who has run this before and knows what they want. +The interactive run is the default, and the flags never change the rule that +nothing is installed without an explicit yes — `--yes` answers the *defaults*. +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from . import actions, detect, menu, render +from .steps import Outcome, Report + +EXIT_OK = 0 +EXIT_FAILED = 2 + + +def parse_args(argv=None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="nerveforge install", + description="Install and start NerveForge, step by step. Without flags it " + "asks a few questions, shows what it found, and starts the bridge.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "Examples:\n" + " nerveforge install interactive, recommended\n" + " nerveforge install --plan print what it would change, change nothing\n" + " nerveforge install --yes accept the defaults; install nothing extra\n" + " nerveforge install --tunnel cloudflared --workspace ~/Projects\n" + " nerveforge install --json --plan the same plan, for another program\n" + " nerveforge install --uninstall remove what this installer created\n" + )) + parser.add_argument("--plan", action="store_true", + help="print every step and what it would change, then exit") + parser.add_argument("--yes", "-y", action="store_true", + help="accept the defaults for every question (still no surprises: " + "shortcuts and PATH changes default to no)") + parser.add_argument("--tunnel", choices=("auto", "cloudflared", "tailscale", "none"), + help="which tunnel to use (default: ask, or auto)") + parser.add_argument("--workspace", metavar="PATH", + help="folder the agent may work in (default: ~/Projects)") + parser.add_argument("--port", type=int, help="local port for the receiver") + parser.add_argument("--shortcut", dest="shortcut", action="store_true", default=None, + help="write a desktop shortcut") + parser.add_argument("--no-shortcut", dest="shortcut", action="store_false", + help="do not write a desktop shortcut") + parser.add_argument("--command", dest="command", action="store_true", default=None, + help="put a `nerveforge` command in a folder already on PATH") + parser.add_argument("--only", metavar="STEP[,STEP]", + help="run only these steps (python, tunnel, workspace, shortcut, " + "command, self-check, start)") + parser.add_argument("--json", action="store_true", + help="print the report as JSON instead of text") + parser.add_argument("--uninstall", action="store_true", + help="remove the shortcut, the launcher and the downloaded " + "cloudflared, and leave the config, data and workspaces alone") + parser.add_argument("--check", action="store_true", + help="run the read-only checks (Python, program import) and exit") + return parser.parse_args(argv) + + +def answers_from(args: argparse.Namespace) -> dict: + """The flags, as the answers the steps read. Absent flags stay absent.""" + answers: dict = {} + if args.tunnel: + answers["tunnel"] = args.tunnel + if args.workspace: + answers["workspace"] = args.workspace + if args.port: + answers["port"] = args.port + if args.shortcut is not None: + answers["shortcut"] = args.shortcut + if args.command is not None: + answers["command"] = args.command + return answers + + +def main(argv=None) -> int: + from .._version import __version__ + + args = parse_args(argv) + info = detect.find_supported_python() + if args.uninstall: + return uninstall_main(argv=None) + + if args.plan: + report = _plan_report() + if args.json: + print(render.as_json(report)) + else: + print(render.plain_plan(__version__, info.text)) + return EXIT_OK + + if args.check: + report = actions.run(only={"python", "self-check"}, + assume_yes=True, answers={"tunnel": "none"}) + print(render.render(report)) + return EXIT_OK if report.stopped is None else EXIT_FAILED + + answers = answers_from(args) + interactive = bool(sys.stdin and sys.stdin.isatty()) and not args.yes \ + and not args.tunnel and not args.json + if interactive: + print(render.header(__version__, info.text, + Path(__file__).resolve().parents[3])) + answers = menu.collect(read=input, answers=answers) + answers.setdefault("interactive", interactive) + + only = None + if args.only: + only = {part.strip() for part in args.only.split(",") if part.strip()} + unknown = only - {key for key, _ in actions.STEPS} + if unknown: + print(f"unknown step(s): {', '.join(sorted(unknown))}", file=sys.stderr) + print("known: " + ", ".join(key for key, _ in actions.STEPS), file=sys.stderr) + return EXIT_FAILED + + if not args.json: + print(render.header(__version__, info.text, Path(__file__).resolve().parents[3])) + print() + + report = actions.run(answers=answers, assume_yes=args.yes, only=only, + dry_run=False) + if args.json: + print(render.as_json(report)) + else: + print(render.render(report)) + _final_word(report) + return EXIT_OK if report.stopped is None else EXIT_FAILED + + +def _final_word(report: Report) -> None: + """What to do after the run, said once, at the end where it is read.""" + if report.stopped is not None: + return + started = report.get("start") + if started is not None and started.outcome is Outcome.SKIP: + print("\nNext: run ./nerveforge in this folder to start NerveForge.") + + +def _plan_report() -> Report: + """The plan, built from the real steps so it cannot drift from the run.""" + from .render import INTENT + + report = Report(dry_run=True) + for key, _ in actions.STEPS: + from .steps import Step + + step = Step(key=key, title=actions.TITLES.get(key, key)) + if key in actions.CHANGING: + step.changes = (INTENT.get(key, ""),) + report.add(step) + return report + + +# -- uninstall --------------------------------------------------------------- +def uninstall(assume_yes: bool = False) -> Report: + """Remove what the installer created. Config, data and workspaces stay. + + The line is drawn where the operator's own content begins: a shortcut and a + launcher are things the installer wrote and can write again, while the + config holds the token and the data folder holds their skills and audit log. + Deleting those on an `--uninstall` would be a data-loss bug wearing an + installer's clothes. + """ + from .apps import command_targets, remove_shortcut # noqa: F401 + from .steps import Step + + report = Report() + shortcut = report.add(Step(key="shortcut", title="Desktop shortcut")) + removed = remove_shortcut() + if removed: + shortcut.done(", ".join(str(path) for path in removed)) + else: + shortcut.skip("no shortcut was installed") + + command = report.add(Step(key="command", title="`nerveforge` command")) + target = command_targets() + if target is not None and target.exists(): + target.unlink() + command.done(str(target)) + else: + command.skip("no launcher was installed") + + tunnel = report.add(Step(key="tunnel-install", title="Downloaded cloudflared")) + path = actions.bin_dir() / ("cloudflared.exe" if sys.platform.startswith("win") + else "cloudflared") + if path.exists(): + path.unlink() + tunnel.done(str(path)) + else: + tunnel.skip("no downloaded copy") + + kept = report.add(Step(key="kept", title="Configuration and data")) + kept.skip("kept on purpose: token, settings, skills and audit log are yours") + return report + + +def uninstall_main(argv=None) -> int: + args = parse_args(argv or []) + report = uninstall(assume_yes=args.yes) + if args.json: + print(render.as_json(report)) + else: + print(render.render(report)) + return EXIT_OK diff --git a/src/nerveforge/installer/detect.py b/src/nerveforge/installer/detect.py new file mode 100644 index 0000000..53a12b2 --- /dev/null +++ b/src/nerveforge/installer/detect.py @@ -0,0 +1,184 @@ +"""Environment probes. Each returns a fact; none of them raises. + +An installer that crashes on a missing binary is an installer that tells the +operator nothing. So every probe here returns either a value or `None`, and the +step that uses it decides what a `None` means. + +The probes are separated from the steps for one practical reason: this is the +part that differs between CI, a development container, and the operator's +machine, and it is the part a test can fake without a filesystem or a network. +""" +from __future__ import annotations + +import platform +import shutil +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +MINIMUM_PYTHON = (3, 10) + + +@dataclass(frozen=True) +class PythonInfo: + """The interpreter that would run the bridge, and whether it is new enough.""" + + executable: str + version: tuple[int, int, int] + + @property + def text(self) -> str: + return ".".join(str(part) for part in self.version) + + @property + def supported(self) -> bool: + return self.version[:2] >= MINIMUM_PYTHON + + def as_dict(self) -> dict: + return {"executable": self.executable, "version": self.text, + "supported": self.supported} + + +def python_info(executable: str | None = None) -> PythonInfo: + """The interpreter running this code, or the one named by `executable`.""" + if executable and Path(executable) != Path(sys.executable): + return _probe_python(executable) + return PythonInfo(sys.executable, tuple(sys.version_info[:3])) # type: ignore[arg-type] + + +def _probe_python(executable: str) -> PythonInfo: + """Ask another interpreter its version, without importing anything of ours.""" + try: + done = subprocess.run( + [executable, "-c", + "import sys; print('%d.%d.%d' % sys.version_info[:3])"], + capture_output=True, text=True, timeout=20, check=False) # noqa: S603 + except (OSError, subprocess.SubprocessError): + return PythonInfo(executable, (0, 0, 0)) + parts = (done.stdout or "").strip().split(".") + try: + version = tuple(int(part) for part in parts[:3]) + except ValueError: + version = (0, 0, 0) + if len(version) != 3: + version = (0, 0, 0) + return PythonInfo(executable, version) # type: ignore[arg-type] + + +def candidates_for_python() -> list[str]: + """Interpreters to try, best first, when the current one is too old. + + A 3.9 interpreter cannot install for a 3.10 bridge, so the installer has to + be able to look around rather than only report that it is stuck. + """ + names = ["python3.13", "python3.12", "python3.11", "python3.10", "python3", "python"] + if platform.system() == "Windows": + names = ["py", "python", "python3"] + found: list[str] = [] + for name in names: + path = shutil.which(name) + if path and path not in found: + found.append(path) + return found + + +def find_supported_python(preferred: str | None = None) -> PythonInfo: + """`preferred` if it is new enough, else the best candidate, else the current. + + The last resort is returned anyway, with `supported` false: the caller's + step turns that into a failure with a remedy, which is more useful than an + exception raised here. + """ + current = python_info(preferred) if preferred else python_info() + if current.supported: + return current + for path in candidates_for_python(): + probe = _probe_python(path) + if probe.supported: + return probe + return current + + +def package_manager() -> str | None: + """The system package manager, if this platform has one we know.""" + system = platform.system() + if system == "Linux": + for name in ("apt-get", "dnf", "pacman", "zypper", "apk"): + if shutil.which(name): + return name + return None + if system == "Darwin": + return "brew" if shutil.which("brew") else None + if system == "Windows": + return "winget" if shutil.which("winget") else None + return None + + +def is_termux() -> bool: + """Termux sets PREFIX to its own usr directory, and nothing else does.""" + import os + + prefix = os.environ.get("PREFIX", "") + return "com.termux" in prefix or bool(os.environ.get("TERMUX_VERSION")) + + +def cloudflared() -> str | None: + """The cloudflared the bridge would use: its own download first, then PATH. + + The same order the tunnel provider uses, through the same function, so the + installer cannot disagree with the panel about whether it is installed. + """ + from ..tunnel import install as tunnel_install + + try: + return tunnel_install.find_binary() + except Exception: # noqa: BLE001 — a probe never raises + return shutil.which("cloudflared") or shutil.which("cloudflared.exe") + + +def tailscale() -> str | None: + return shutil.which("tailscale") or shutil.which("tailscale.exe") + + +def tunnel_clients() -> dict: + """Both clients, with the path that would actually be executed.""" + return {"cloudflared": cloudflared(), "tailscale": tailscale()} + + +def writable_directory(path: Path) -> bool: + """Whether a directory can be created and written to, without leaving junk.""" + try: + path.mkdir(parents=True, exist_ok=True) + probe = path / ".nerveforge-write-probe" + probe.write_text("", encoding="utf-8") + probe.unlink() + return True + except OSError: + return False + + +def desktop_environment() -> bool: + """Whether a `.desktop` shortcut would mean anything on this machine.""" + import os + + if platform.system() != "Linux": + return False + if is_termux(): + return False + return bool(os.environ.get("XDG_CURRENT_DESKTOP") or os.environ.get("DISPLAY") + or os.environ.get("WAYLAND_DISPLAY")) + + +def admin() -> bool: + """Whether this process is elevated. Windows and POSIX disagree on how.""" + import os + + if os.name == "nt": # pragma: no cover - Windows only + import ctypes + + try: + return bool(ctypes.windll.shell32.IsUserAnAdmin()) + except (AttributeError, OSError): + return False + return hasattr(os, "geteuid") and os.geteuid() == 0 diff --git a/src/nerveforge/installer/menu.py b/src/nerveforge/installer/menu.py new file mode 100644 index 0000000..fe1b07a --- /dev/null +++ b/src/nerveforge/installer/menu.py @@ -0,0 +1,149 @@ +"""The questions, and the one rule that shapes all of them. + +The rule: **nothing that changes this machine happens without a yes.** Not a +download, not a shortcut, not a folder outside the user's data directory. What +the installer *finds* is reported without asking, because a check is not a +change. + +The questions are collected before the steps run, so a run can be planned, +echoed back, and answered identically by a script (`--yes`, `--tunnel`, +`--workspace`). That is also why they are ordinary functions taking a callable +for input: a test can answer them without a terminal. +""" +from __future__ import annotations + +from pathlib import Path + +from . import detect + +YES = {"y", "yes", "д", "да"} + + +def ask(prompt: str, *, default: bool, stream=None, read=None) -> bool: + """One yes/no question, with the default in the prompt and on an empty line.""" + read = read or input + hint = "[Y/n]" if default else "[y/N]" + try: + answer = str(read(f"{prompt} {hint} ")).strip().lower() + except (EOFError, OSError, KeyboardInterrupt): + # No terminal, or the operator pressed Ctrl+C on a question: the safe + # answer is the one that changes nothing. + return False + if not answer: + return default + return answer in YES + + +def ask_text(prompt: str, *, default: str, read=None) -> str: + read = read or input + try: + answer = str(read(f"{prompt} [{default}] ")).strip() + except (EOFError, OSError, KeyboardInterrupt): + return default + return answer or default + + +def ask_choice(prompt: str, options: list[tuple[str, str]], *, default: str, + read=None) -> str: + """Numbered choice; the number or the value both work.""" + read = read or input + print(prompt) + for number, (value, label) in enumerate(options, 1): + marker = "*" if value == default else " " + print(f" {number}.{marker} {label}") + answer = "" + try: + answer = str(read(f"Choice [{default}] ")).strip().lower() + except (EOFError, OSError, KeyboardInterrupt): + return default + if not answer: + return default + if answer.isdigit() and 1 <= int(answer) <= len(options): + return options[int(answer) - 1][0] + for value, _ in options: + if answer == value: + return value + return default + + +def collect(*, read=None, answers: dict | None = None, assume_yes: bool = False) -> dict: + """Ask everything the run needs, in the order a person would decide it. + + `assume_yes` answers the *default* to every question rather than yes to all + of them: `--yes` on a headless server should install nothing it would have + asked about, and a shortcut on a server is exactly the surprise to avoid. + """ + given = dict(answers or {}) + found = detect.tunnel_clients() + collected: dict = {} + + if "tunnel" not in given: + if found["cloudflared"]: + collected["tunnel"] = "cloudflared" + elif found["tailscale"]: + collected["tunnel"] = "tailscale" + elif assume_yes: + collected["tunnel"] = "none" + else: + print("\nA tunnel makes the panel reachable from anywhere.") + if found["cloudflared"] or found["tailscale"]: + pass + collected["tunnel"] = ask_choice( + "No tunnel client is installed. Choose how to reach the panel:", + [("cloudflared", "Cloudflare Quick Tunnel (no account; the address " + "changes on every start)"), + ("none", "Local only (works now; no public address)")], + default="cloudflared" if not assume_yes else "none", read=read) + + tunnel = collected.get("tunnel", given.get("tunnel", "auto")) + if "install_tunnel" not in given: + if tunnel == "cloudflared" and not found["cloudflared"]: + collected["install_tunnel"] = ( + True if assume_yes else + ask("Download cloudflared (~40 MB) into your data folder?", + default=True, read=read)) + elif tunnel == "cloudflared": + collected["install_tunnel"] = False + else: + collected["install_tunnel"] = False + + if "workspace" not in given: + from .. import paths + + default = str(paths.workspace_dir()) + chosen = ("" if assume_yes or read is None + else ask_text("Folder the agent may work in", default=default, read=read)) + collected["workspace"] = chosen or default + + if "shortcut" not in given: + if detect.desktop_environment(): + collected["shortcut"] = (False if assume_yes else + ask("Add a desktop shortcut?", default=True, read=read)) + else: + collected["shortcut"] = False + + if "command" not in given: + collected["command"] = (False if assume_yes else + ask("Add a `nerveforge` command to your PATH?", default=False, + read=read)) + + if "start" not in given: + collected["start"] = (True if assume_yes else + ask("Start NerveForge now?", default=True, read=read)) + + merged = {**given, **collected} + return merged + + +def confirm_plan(report, *, read=None) -> bool: + """Show what would change and ask once, instead of asking at every step.""" + from .render import plan_lines + + for line in plan_lines(report): + print(line) + return ask("Apply this plan?", default=True, read=read) + + +def workspace_from_text(text: str) -> Path: + """Expand a path the way a shell would, for display and for the step.""" + return Path(text).expanduser() diff --git a/src/nerveforge/installer/render.py b/src/nerveforge/installer/render.py new file mode 100644 index 0000000..454e267 --- /dev/null +++ b/src/nerveforge/installer/render.py @@ -0,0 +1,147 @@ +"""Turning a report into text. One place, so the screen and `--json` never differ. + +Two audiences read this: a person watching a terminal, who wants to see the +step that is running right now and why it stopped, and another program, which +wants the same facts without the box drawing. +""" +from __future__ import annotations + +import json +from pathlib import Path + +from .steps import Report, Step + +WIDTH = 72 + + +def header(version: str, python: str, root: Path) -> str: + """The two lines that say which program is running, and from where.""" + rule = "=" * WIDTH + return "\n".join([ + rule, + f" NerveForge {version} — installer", + f" Python {python} · {root}", + rule, + ]) + + +#: Column where the detail starts. Wide enough for the longest step title plus +#: its number, so the details line up no matter which step is being printed. +DETAIL_COLUMN = 34 + + +def step_line(step: Step, *, dry_run: bool = False) -> str: + """One step, as it is printed while it runs. + + The detail wraps under its own column rather than under the step mark: a + path split at the margin is unreadable, and a path is most of what these + lines say. + """ + mark = "would" if dry_run and step.outcome.value == "done" else step.outcome.icon + left = f"{mark:>5} {_n(step.index)}. {step.title}" + head = f"{left:<{DETAIL_COLUMN}} " + # Continuation lines are indented to the detail column, so a wrapped path + # reads as one value rather than as another step's detail. + wrapped = _wrap(step.detail, width=max(24, 100 - DETAIL_COLUMN), + subsequent_indent=" " * DETAIL_COLUMN) + return head + wrapped + + +def _n(index: int) -> str: + return f"{index:>2}" + + +def _wrap(text: str, width: int, subsequent_indent: str = "") -> str: + from textwrap import wrap + + lines = wrap(text, width=max(20, width), subsequent_indent=subsequent_indent) + return "\n".join(lines) or "" + + +def render(report: Report, *, colour: bool = False) -> str: + """The full run, step by step, then the verdict and any remedies.""" + lines: list[str] = [] + for index, step in enumerate(report, 1): + step.index = index # type: ignore[attr-defined] + lines.append(step_line(step, dry_run=report.dry_run)) + lines.append("") + stopped = report.stopped + if stopped is not None: + lines.append(f"Stopped at step {stopped.index}: {stopped.detail}") # type: ignore[attr-defined] + if stopped.remedy: + lines.append(f"What to do: {stopped.remedy}") + else: + failures = [step for step in report.failed if not step.fatal] + if failures: + for step in failures: + lines.append(f"Warning at step {step.index}: {step.detail}") # type: ignore[attr-defined] + if step.remedy: + lines.append(f" {step.remedy}") + lines.append(report.summary()) + return "\n".join(lines) + + +def plan_lines(report: Report) -> list[str]: + """What a run would do, phrased as conditions rather than results. + + The line for each changing step is written before the run, so it can only + say what the step is *for*; that is exactly what a person deciding whether + to run it needs. + """ + lines = ["This plan would:"] + for index, step in enumerate(report, 1): + if step.changes: + lines.append(f" {index}. {step.title}: {'; '.join(step.changes)}") + if len(lines) == 1: + lines.append(" change nothing — every step found its work already done") + return lines + + +def as_dict(report: Report) -> dict: + """The machine-readable answer, used by `--json` and by the tests.""" + return { + "dry_run": report.dry_run, + "summary": report.summary(), + "stopped": report.stopped.key if report.stopped else None, + "steps": [ + {"key": step.key, "title": step.title, "outcome": step.outcome.value, + "detail": step.detail, "remedy": step.remedy, "fatal": step.fatal, + "changes": list(step.changes)} + for step in report + ], + } + + +def as_json(report: Report) -> str: + return json.dumps(as_dict(report), ensure_ascii=False, indent=2) + + +def plain_plan(version: str, python: str) -> str: + """`--plan` without running anything: the plan the run would produce.""" + report = _plan_report() + lines = [header(version, python, Path.cwd()), ""] + lines += plan_lines(report) + return "\n".join(lines) + + +def _plan_report() -> Report: + """A plan-only report: every step, with what it intends to change.""" + from .actions import CHANGING, STEPS, TITLES + + report = Report(dry_run=True) + for key, _ in STEPS: + step = Step(key=key, title=TITLES.get(key, key)) + if key in CHANGING: + step.changes = (INTENT.get(key, ""),) + report.add(step) + return report + + +#: What each changing step intends, in the words `--plan` prints. +INTENT = { + "tunnel-install": "download cloudflared into the data folder, if it is the chosen tunnel", + "state": "create the config and data folders", + "workspace": "create the working folder if it does not exist", + "shortcut": "write an application-menu entry (desktop sessions only)", + "command": "write a launcher into a folder already on PATH", +} diff --git a/src/nerveforge/installer/steps.py b/src/nerveforge/installer/steps.py new file mode 100644 index 0000000..c629c5a --- /dev/null +++ b/src/nerveforge/installer/steps.py @@ -0,0 +1,142 @@ +"""The step model: one step, three outcomes, one report. + +Every installer step — checking Python, choosing a tunnel, writing a shortcut — +answers the same three questions in the same shape, because the screen and the +exit code both need to be able to say "stopped here, for this reason" without +special-casing any particular step. + +The vocabulary is small on purpose: + +``DONE`` + The step changed something on this machine and it worked. +``SKIP`` + The step found the work already done, or the operator chose not to do it. + A skip is not a failure and must carry the reason, or it looks like a bug. +``FAIL`` + The step cannot continue, and the report says what to do about it. +""" +from __future__ import annotations + +import enum +from dataclasses import dataclass, field + + +class Outcome(str, enum.Enum): + """What happened to one step. A string enum so it can be printed raw.""" + + DONE = "done" + SKIP = "skip" + FAIL = "fail" + + @property + def icon(self) -> str: + return {"done": "[ok]", "skip": "[--]", "fail": "[x]"}[self.value] + + +@dataclass +class Step: + """One thing the installer does, and everything needed to explain it.""" + + key: str # stable id: used by --only and by the tests + title: str # what the screen says + outcome: Outcome = Outcome.SKIP + detail: str = "" # one line: what was found, or why it stopped + changes: tuple[str, ...] = () # what this step would change, for --plan + #: A failure that a later step can still work around (no tunnel found, but + #: local mode is fine). Distinguishes "stop" from "carry on with a caveat". + fatal: bool = False + #: What the operator can do next, when the outcome is FAIL. + remedy: str = "" + + def done(self, detail: str = "") -> Step: + self.outcome, self.detail = Outcome.DONE, detail or self.detail + return self + + def skip(self, detail: str = "", fatal: bool = False) -> Step: + self.outcome, self.detail = Outcome.SKIP, detail or self.detail + self.fatal = fatal + return self + + def fail(self, detail: str = "", *, remedy: str = "", fatal: bool = True) -> Step: + self.outcome, self.detail = Outcome.FAIL, detail or self.detail + self.remedy = remedy + self.fatal = fatal + return self + + @property + def ok(self) -> bool: + """Whether a run with this step in it may continue.""" + return not (self.outcome is Outcome.FAIL and self.fatal) + + +@dataclass +class Report: + """The whole run: the steps in order, and the verdict on them.""" + + steps: list[Step] = field(default_factory=list) + dry_run: bool = False + + def add(self, step: Step) -> Step: + self.steps.append(step) + return step + + def __iter__(self): + return iter(self.steps) + + def get(self, key: str) -> Step | None: + for step in self.steps: + if step.key == key: + return step + return None + + @property + def stopped(self) -> Step | None: + """The first fatal failure, if the run could not finish.""" + for step in self.steps: + if step.outcome is Outcome.FAIL and step.fatal: + return step + return None + + @property + def failed(self) -> list[Step]: + return [step for step in self.steps if step.outcome is Outcome.FAIL] + + @property + def changed(self) -> bool: + """Whether anything on this machine would be different afterwards.""" + return any(step.outcome is Outcome.DONE and step.changes for step in self.steps) + + def summary(self) -> str: + done = sum(1 for step in self.steps if step.outcome is Outcome.DONE) + skipped = sum(1 for step in self.steps if step.outcome is Outcome.SKIP) + failed = len(self.failed) + return (f"{done} done, {skipped} skipped, {failed} failed" + + (" (plan only, nothing changed)" if self.dry_run else "")) + + +class StepContext: + """Everything a step needs, so a step never reaches for globals. + + `answers` holds the operator's decisions collected up front: a step that + needs to ask something reads it from here rather than blocking on input in + the middle of a run, which is what makes `--plan` possible at all. + """ + + def __init__(self, *, answers: dict | None = None, assume_yes: bool = False, + dry_run: bool = False, root=None, python=None, platform=None, + stream=None): + self.answers = dict(answers or {}) + self.assume_yes = assume_yes + self.dry_run = dry_run + self.root = root + self.python = python + self.platform = platform + self.stream = stream + + def answer(self, key: str, default=None): + return self.answers.get(key, default) + + def say(self, text: str = "") -> None: + """One line of installer output, in the language the plan was written.""" + if self.stream is not None: + print(text, file=self.stream, flush=True) diff --git a/tests/test_installer.py b/tests/test_installer.py new file mode 100644 index 0000000..824a8ad --- /dev/null +++ b/tests/test_installer.py @@ -0,0 +1,574 @@ +"""The installer: the step model, the refusals, and what it leaves behind. + +The properties worth testing here are not "the happy path prints a banner". They +are the promises the old shell scripts could only make in a comment: + +* every stop names a reason and a remedy, and none of them is a stack trace; +* nothing that changes the machine happens without an explicit yes; +* running it twice is not two installs; +* `--plan` changes nothing, and says the same thing the run would do; +* `--uninstall` removes the installer's own files and leaves the operator's + token, skills and audit log alone. + +Every filesystem effect goes through `tmp` (HOME is patched), so a test can +assert on the result rather than on a mocked call. +""" +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from nerveforge.installer import actions, apps, cli, detect, menu, render # noqa: E402 +from nerveforge.installer.steps import Outcome, Report, Step, StepContext # noqa: E402 + + +class TempHome(unittest.TestCase): + """Every test gets its own HOME, so nothing touches the real one.""" + + def setUp(self): + self.home = tempfile.TemporaryDirectory() + self.addCleanup(self.home.cleanup) + self.root = Path(self.home.name) + patchers = [ + mock.patch.dict(os.environ, {"HOME": str(self.root), "USERPROFILE": str(self.root)}), + mock.patch.object(Path, "home", return_value=self.root), + ] + for patcher in patchers: + patcher.start() + self.addCleanup(patcher.stop) + + def ctx(self, **answers): + info = detect.PythonInfo(sys.executable, tuple(sys.version_info[:3])) + answers.setdefault("tunnel", "none") + return StepContext(answers=answers, root=Path(__file__).resolve().parents[1], + python=lambda: info) + + +class PythonStepTests(TempHome): + def test_a_new_enough_python_passes_with_its_path(self): + step = actions.check_python(self.ctx(), Step("python", "Python")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertIn("Python", step.detail) + + def test_an_old_python_fails_with_a_remedy_a_person_can_follow(self): + info = detect.PythonInfo("/usr/bin/python3", (3, 9, 9)) + ctx = StepContext(answers={"tunnel": "none"}, python=lambda: info) + step = actions.check_python(ctx, Step("python", "Python")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("3.9", step.detail) + self.assertIn("3.10", step.remedy) + + def test_an_unreadable_interpreter_is_not_called_supported(self): + self.assertFalse(detect._probe_python("/nonexistent/python").supported) + + def test_a_fake_interpreter_is_probed_by_running_it(self): + fake = self.root / "python3.9" + fake.write_text("#!/bin/sh\necho 3.9.1\n", encoding="utf-8") + fake.chmod(0o755) + info = detect._probe_python(str(fake)) + self.assertEqual(info.version[:2], (3, 9)) + self.assertFalse(info.supported) + + +class ElevationTests(TempHome): + def test_a_normal_user_is_told_so_without_a_warning(self): + with mock.patch.object(detect, "admin", return_value=False): + step = actions.check_elevation(self.ctx(), Step("elevation", "Rights")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertIn("normal user", step.detail) + + def test_running_as_admin_is_reported_as_a_risk(self): + with mock.patch.object(detect, "admin", return_value=True): + step = actions.check_elevation(self.ctx(), Step("elevation", "Rights")) + self.assertIn("administrator", step.detail) + self.assertIn("system settings", step.detail) + + +class TunnelStepTests(TempHome): + def clients(self, cloudflared=None, tailscale=None): + return mock.patch.object(detect, "tunnel_clients", + return_value={"cloudflared": cloudflared, + "tailscale": tailscale}) + + def test_local_mode_is_a_working_mode_not_a_failure(self): + step = actions.choose_tunnel(self.ctx(tunnel="none"), Step("tunnel", "Tunnel")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertIn("local", step.detail) + + def test_auto_prefers_cloudflared_then_tailscale_then_nothing(self): + cases = [(("c", None), "cloudflared"), ((None, "t"), "tailscale"), + ((None, None), "local")] + for (cloudflared, tailscale), expected in cases: + with self.subTest(cloudflared=cloudflared, tailscale=tailscale): + with self.clients(cloudflared, tailscale): + step = actions.choose_tunnel(self.ctx(tunnel="auto"), + Step("tunnel", "Tunnel")) + self.assertIn(expected, step.detail) + + def test_choosing_cloudflared_without_it_and_without_consent_stops_the_run(self): + with self.clients(): + step = actions.choose_tunnel(self.ctx(tunnel="cloudflared"), + Step("tunnel", "Tunnel")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("declined", step.detail) + self.assertIn("--tunnel none", step.remedy) + + def test_choosing_cloudflared_with_consent_is_a_done_not_a_download(self): + with self.clients(): + step = actions.choose_tunnel(self.ctx(tunnel="cloudflared", install_tunnel=True), + Step("tunnel", "Tunnel")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertIn("downloaded next", step.detail) + + def test_a_missing_tailscale_is_a_stop_because_it_is_not_a_download(self): + with self.clients(): + step = actions.choose_tunnel(self.ctx(tunnel="tailscale"), + Step("tunnel", "Tunnel")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("tailscale.com", step.remedy) + + def test_a_download_that_fails_does_not_hide_behind_a_started_tunnel(self): + + with mock.patch.object(detect, "tunnel_clients", + return_value={"cloudflared": None, "tailscale": None}), \ + mock.patch.object(actions, "bin_dir", return_value=self.root / "bin"): + from nerveforge.tunnel import install as tunnel_install + + with mock.patch.object(tunnel_install, "resolve_release", + side_effect=tunnel_install.InstallError("no route")): + step = actions.install_tunnel( + self.ctx(tunnel="cloudflared", install_tunnel=True), + Step("tunnel-install", "Download")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("no route", step.detail) + self.assertIn("locally", step.remedy) + self.assertFalse(step.fatal, "a blocked download must not stop a working install") + + +class WorkspaceStepTests(TempHome): + def test_a_missing_folder_is_created(self): + target = self.root / "projects" / "work" + step = actions.prepare_workspace(self.ctx(workspace=str(target)), + Step("workspace", "Folder")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertTrue(target.is_dir()) + + def test_a_relative_path_is_refused_with_the_reason(self): + step = actions.prepare_workspace(self.ctx(workspace="relative/dir"), + Step("workspace", "Folder")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("absolute", step.detail) + self.assertIn("--workspace", step.remedy) + + def test_an_unwritable_folder_is_refused_before_the_agent_needs_it(self): + blocked = self.root / "blocked" + blocked.mkdir() + blocked.chmod(0o500) + self.addCleanup(blocked.chmod, 0o700) + if os.geteuid() == 0: # root can write anywhere + self.skipTest("running as root") + step = actions.prepare_workspace(self.ctx(workspace=str(blocked)), + Step("workspace", "Folder")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("cannot be written", step.detail) + + def test_a_dry_run_creates_nothing(self): + target = self.root / "would-be" + ctx = self.ctx(workspace=str(target)) + ctx.dry_run = True + step = actions.prepare_workspace(ctx, Step("workspace", "Folder")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertFalse(target.exists()) + + +class ShortcutTests(TempHome): + def test_no_desktop_means_no_shortcut_and_a_sentence_saying_so(self): + with mock.patch.object(detect, "desktop_environment", return_value=False), \ + mock.patch.object(detect, "is_termux", return_value=False): + step = actions.install_shortcut(self.ctx(), Step("shortcut", "Shortcut")) + self.assertIs(step.outcome, Outcome.SKIP) + self.assertIn("./nerveforge", step.detail) + + def test_termux_says_why_there_is_no_menu_entry(self): + with mock.patch.object(detect, "desktop_environment", return_value=False), \ + mock.patch.object(detect, "is_termux", return_value=True): + step = actions.install_shortcut(self.ctx(), Step("shortcut", "Shortcut")) + self.assertIs(step.outcome, Outcome.SKIP) + self.assertIn("Termux", step.detail) + + def test_a_desktop_entry_is_written_when_asked_on_a_desktop(self): + with mock.patch.object(detect, "desktop_environment", return_value=True): + step = actions.install_shortcut(self.ctx(shortcut=True), + Step("shortcut", "Shortcut")) + self.assertIs(step.outcome, Outcome.DONE) + entry = self.root / ".local" / "share" / "applications" / "nerveforge.desktop" + self.assertTrue(entry.is_file()) + text = entry.read_text(encoding="utf-8") + self.assertIn("[Desktop Entry]", text) + self.assertIn("Name=NerveForge", text) + self.assertIn("Terminal=true", text) + + def test_the_desktop_entry_quotes_paths_with_spaces(self): + entry = apps.desktop_entry(Path("/opt/my apps/Neuro"), "/usr/bin/python3") + self.assertIn('"/opt/my apps/Neuro/run.py"', entry) + + def test_a_desktop_entry_without_an_icon_does_not_invent_one(self): + entry = apps.desktop_entry(self.root, "/usr/bin/python3") + self.assertNotIn("Icon=", entry) + + +class CommandStepTests(TempHome): + def test_putting_a_launcher_on_path_needs_a_yes(self): + step = actions.install_command(self.ctx(), Step("command", "Command")) + self.assertIs(step.outcome, Outcome.SKIP) + self.assertIn("--command", step.detail) + + def test_a_launcher_is_a_python_file_with_an_absolute_root(self): + target = self.root / ".local" / "bin" / "nerveforge" + with mock.patch.object(apps, "command_targets", return_value=target): + step = actions.install_command(self.ctx(command=True), Step("command", "Command")) + self.assertIs(step.outcome, Outcome.DONE) + text = target.read_text(encoding="utf-8") + self.assertIn("runpy.run_module", text) + self.assertIn(str(Path(__file__).resolve().parents[1]), text) + if not sys.platform.startswith("win"): + self.assertTrue(os.access(target, os.X_OK)) + + def test_only_a_user_directory_on_path_is_chosen(self): + with mock.patch.dict(os.environ, {"PATH": "/usr/bin:/bin"}), \ + mock.patch.object(Path, "home", return_value=self.root): + self.assertIsNone(apps.command_targets()) + local = self.root / ".local" / "bin" + local.mkdir(parents=True) + with mock.patch.dict(os.environ, {"PATH": f"/usr/bin:{local}"}): + self.assertEqual(apps.command_targets(), local / "nerveforge") + + +class SelfCheckTests(TempHome): + def test_the_tree_loads_and_reports_its_routes(self): + step = actions.self_check(self.ctx(), Step("self-check", "Check")) + self.assertIs(step.outcome, Outcome.DONE) + self.assertIn("routes", step.detail) + + def test_a_broken_tree_fails_with_a_remedy_instead_of_a_traceback(self): + import builtins + + real_import = builtins.__import__ + + def refuse(name, *args, **kwargs): + if name.endswith("_version"): + raise ImportError("simulated broken tree") + return real_import(name, *args, **kwargs) + + with mock.patch("builtins.__import__", side_effect=refuse): + step = actions.self_check(self.ctx(), Step("self-check", "Check")) + self.assertIs(step.outcome, Outcome.FAIL) + self.assertIn("simulated broken tree", step.detail) + self.assertIn("Re-clone", step.remedy) + + +class DetectTests(TempHome): + def test_a_windows_layout_is_recognised_before_anything_is_written(self): + self.assertIn(detect.package_manager.__name__, ("package_manager",)) + + def test_the_data_bin_is_one_folder_for_the_panel_and_the_installer(self): + from nerveforge import paths + + self.assertEqual(actions.bin_dir(), paths.data_dir() / "bin") + + def test_package_manager_is_a_name_or_none_never_a_guess(self): + manager = detect.package_manager() + self.assertTrue(manager is None or manager.islower()) + + def test_termux_is_detected_by_its_own_marker_not_by_android(self): + with mock.patch.dict(os.environ, {"PREFIX": "/data/data/com.termux/files/usr"}): + self.assertTrue(detect.is_termux()) + with mock.patch.dict(os.environ, {"PREFIX": "/usr"}, clear=False): + self.assertFalse(detect.is_termux()) + + def test_an_unwritable_home_is_a_named_problem_not_a_crash(self): + self.assertTrue(detect.writable_directory(self.root)) + blocked = self.root / "readonly" + blocked.mkdir() + blocked.chmod(0o500) + self.addCleanup(blocked.chmod, 0o700) + if os.geteuid() == 0: + self.skipTest("running as root") + self.assertFalse(detect.writable_directory(blocked)) + + +class RunTests(TempHome): + def test_a_fatal_failure_stops_the_run_at_that_step(self): + info = detect.PythonInfo("/usr/bin/python", (3, 8, 0)) + with mock.patch.object(detect, "find_supported_python", return_value=info): + report = actions.run(answers={"tunnel": "none"}, assume_yes=True) + self.assertEqual(report.stopped.key, "python") + self.assertEqual([step.key for step in report], ["python"]) + self.assertTrue(report.steps[0].fatal) + + def test_a_non_fatal_failure_lets_the_run_finish(self): + # run() dispatches through STEPS, so the fake has to be in there. + replaced = tuple((key, (lambda ctx, step: step.fail("no desktop", fatal=False)) + if key == "shortcut" else fn) + for key, fn in actions.STEPS) + with mock.patch.object(actions, "STEPS", replaced): + report = actions.run(only={"shortcut", "self-check"}, + answers={"tunnel": "none"}, assume_yes=True) + self.assertIsNone(report.stopped) + self.assertEqual(len(report.failed), 1) + + def test_a_step_that_raises_becomes_a_reported_failure(self): + def explode(ctx, step): + raise RuntimeError("boom") + + replaced = (("python", explode),) + tuple(actions.STEPS[1:]) + with mock.patch.object(actions, "STEPS", replaced): + report = actions.run(answers={"tunnel": "none"}, assume_yes=True) + self.assertIs(report.stopped.outcome, Outcome.FAIL) + self.assertIn("boom", report.stopped.detail) + + def test_only_runs_the_named_steps(self): + report = actions.run(only={"self-check"}, answers={"tunnel": "none"}) + self.assertEqual([step.key for step in report], ["self-check"]) + + def test_running_twice_does_not_create_two_of_anything(self): + answers = {"tunnel": "none", "workspace": str(self.root / "ws"), + "shortcut": True} + with mock.patch.object(detect, "desktop_environment", return_value=True): + first = actions.run(only={"state", "workspace", "shortcut"}, answers=answers) + second = actions.run(only={"state", "workspace", "shortcut"}, answers=answers) + self.assertIsNone(first.stopped) + entries = list((self.root / ".local" / "share" / "applications").iterdir()) + self.assertEqual([path.name for path in entries], ["nerveforge.desktop"]) + self.assertIsNone(second.stopped) + + +class PlanTests(TempHome): + def test_the_plan_lists_the_changing_steps_and_nothing_else(self): + report = cli._plan_report() + keys = [step.key for step in report] + self.assertEqual(keys, [key for key, _ in actions.STEPS]) + changing = {step.key for step in report if step.changes} + self.assertEqual(changing, set(actions.CHANGING)) + + def test_the_plan_changes_nothing(self): + before = sorted(path.name for path in self.root.iterdir()) + report = cli._plan_report() + self.assertFalse(report.changed) + self.assertTrue(report.dry_run) + self.assertEqual(sorted(path.name for path in self.root.iterdir()), before) + + def test_plan_output_is_human_readable_and_mentions_each_change(self): + text = render.plain_plan("9.9.9", "3.12.0") + self.assertIn("installer", text) + self.assertIn("This plan would", text) + self.assertIn("cloudflared", text) + self.assertIn("working folder", text) + + def test_plan_lists_what_it_would_change_in_a_dry_run_report(self): + report = cli._plan_report() + lines = render.plan_lines(report) + self.assertTrue(lines[0].startswith("This plan would")) + self.assertGreater(len(lines), 1) + + +class ReportTests(unittest.TestCase): + def test_summary_counts_each_outcome(self): + report = Report() + report.add(Step("a", "A").done()) + report.add(Step("b", "B").skip("nothing to do")) + report.add(Step("c", "C").fail("broken")) + self.assertEqual(report.summary(), "1 done, 1 skipped, 1 failed") + + def test_a_skipped_fatal_step_is_not_a_failure(self): + step = Step("a", "A").skip("chose not to") + self.assertTrue(step.ok) + self.assertIsNone(Report([step]).stopped) + + def test_json_carries_every_field_a_script_would_want(self): + report = Report() + report.add(Step("a", "A").fail("boom", remedy="fix it")) + payload = json.loads(render.as_json(report)) + self.assertEqual(payload["stopped"], "a") + self.assertEqual(payload["steps"][0]["remedy"], "fix it") + self.assertIs(payload["dry_run"], False) + + def test_a_step_icon_is_never_blank(self): + for outcome in Outcome: + self.assertTrue(outcome.icon.strip()) + + +class MenuTests(unittest.TestCase): + def answers(self, *replies): + queue = list(replies) + return lambda prompt="": queue.pop(0) if queue else "" + + def test_an_empty_answer_takes_the_default(self): + self.assertTrue(menu.ask("Add?", default=True, read=self.answers(""))) + self.assertFalse(menu.ask("Add?", default=False, read=self.answers(""))) + + def test_yes_and_no_in_both_languages(self): + for word in ("y", "Y", "yes", "д", "да"): + self.assertTrue(menu.ask("Add?", default=False, read=self.answers(word)), word) + for word in ("n", "no", "н", "нет"): + self.assertFalse(menu.ask("Add?", default=True, read=self.answers(word)), word) + + def test_closing_the_terminal_answers_no(self): + def close(prompt=""): + raise EOFError + + self.assertFalse(menu.ask("Install?", default=True, read=close)) + + def test_a_choice_accepts_a_number_or_a_word(self): + read = self.answers("2") + self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("b", "B")], + default="a", read=read), "b") + read = self.answers("tailscale") + self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("tailscale", "T")], + default="a", read=read), "tailscale") + + def test_a_nonsense_choice_takes_the_default(self): + self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("b", "B")], + default="a", read=self.answers("nonsense")), "a") + + +class CliTests(TempHome): + def test_plan_exits_zero_and_prints_before_touching_anything(self): + with mock.patch("builtins.print") as printed: + code = cli.main(["--plan"]) + self.assertEqual(code, 0) + self.assertTrue(printed.called) + + def test_check_runs_only_the_read_only_steps(self): + with mock.patch("builtins.print"): + code = cli.main(["--check"]) + self.assertEqual(code, 0) + + def test_an_unknown_step_is_named_rather_than_ignored(self): + with mock.patch("builtins.print"): + code = cli.main(["--yes", "--only", "python,nonsense"]) + self.assertEqual(code, 2) + + def test_a_failure_is_a_non_zero_exit_code(self): + with mock.patch("builtins.print"): + code = cli.main(["--yes", "--only", "workspace", + "--workspace", "relative"]) + self.assertEqual(code, 2) + + def test_flags_become_answers_and_absent_flags_stay_absent(self): + args = cli.parse_args(["--tunnel", "none", "--workspace", "/tmp/x"]) + self.assertEqual(cli.answers_from(args), + {"tunnel": "none", "workspace": "/tmp/x"}) + self.assertEqual(cli.answers_from(cli.parse_args([])), {}) + + def test_json_mode_prints_one_json_document(self): + lines = [] + with mock.patch("builtins.print", side_effect=lambda *a, **k: lines.append(a[0])): + code = cli.main(["--json", "--tunnel", "none", "--only", "python"]) + self.assertEqual(code, 0) + payload = json.loads("\n".join(str(line) for line in lines)) + self.assertEqual(payload["steps"][0]["key"], "python") + + +class UninstallTests(TempHome): + def test_it_removes_the_shortcut_and_the_launcher(self): + entry = self.root / ".local" / "share" / "applications" / "nerveforge.desktop" + entry.parent.mkdir(parents=True) + entry.write_text("[Desktop Entry]\n", encoding="utf-8") + launcher = self.root / ".local" / "bin" / "nerveforge" + launcher.parent.mkdir(parents=True) + launcher.write_text("#!/usr/bin/env python3\n", encoding="utf-8") + + with mock.patch.object(apps, "command_targets", return_value=launcher), \ + mock.patch("builtins.print"): + report = cli.uninstall() + self.assertFalse(entry.exists()) + self.assertFalse(launcher.exists()) + self.assertIsNone(report.stopped) + + def test_it_keeps_the_config_data_and_workspaces(self): + config = self.root / ".config" / "nerveforge" / "token" + config.parent.mkdir(parents=True) + config.write_text("secret", encoding="utf-8") + data = self.root / ".local" / "share" / "nerveforge" / "skills" + data.mkdir(parents=True) + + with mock.patch.object(apps, "command_targets", return_value=None), \ + mock.patch.object(actions, "bin_dir", return_value=self.root / "bin"), \ + mock.patch("builtins.print"): + report = cli.uninstall() + self.assertTrue(config.is_file()) + self.assertTrue(data.is_dir()) + kept = report.get("kept") + self.assertIs(kept.outcome, Outcome.SKIP) + self.assertIn("yours", kept.detail) + + def test_a_downloaded_cloudflared_is_removed(self): + binary = self.root / "bin" / "cloudflared" + binary.parent.mkdir(parents=True) + binary.write_bytes(b"#!/bin/sh\n") + + with mock.patch.object(apps, "command_targets", return_value=None), \ + mock.patch.object(actions, "bin_dir", return_value=self.root / "bin"), \ + mock.patch("builtins.print"): + report = cli.uninstall() + self.assertFalse(binary.exists()) + self.assertIs(report.get("tunnel-install").outcome, Outcome.DONE) + + +class WrapperTests(unittest.TestCase): + """The shell scripts are hand-overs, not second implementations.""" + + def read(self, name): + path = Path(__file__).resolve().parents[1] / name + return path.read_text(encoding="utf-8") + + def test_setup_sh_hands_over_to_the_python_installer(self): + text = self.read("setup.sh") + self.assertIn("nerveforge", text) + self.assertIn("install", text) + self.assertIn("3, 10", text) + # The old script ran apt itself; the new one must not. + self.assertNotIn("apt-get install", text) + + def test_setup_termux_installs_python_and_hands_over(self): + text = self.read("setup_termux.sh") + self.assertIn("pkg install", text) + self.assertIn("python", text) + self.assertIn("install", text) + + def test_setup_windows_is_a_hand_over_with_no_installer_of_its_own(self): + text = self.read("setup_windows.ps1") + self.assertIn("nerveforge", text) + self.assertIn("install", text) + self.assertIn("(3, 10)", text) + # The old script carried its own winget installs; the new one must not, + # or the two installers drift apart again. + self.assertNotIn("winget install", text) + self.assertNotIn("Cloudflare.cloudflared", text) + self.assertIn("ValueFromRemainingArguments", text) + + def test_both_scripts_refuse_to_fake_a_result(self): + for name in ("setup.sh", "setup_termux.sh"): + with self.subTest(name=name): + self.assertIn("exit 2", self.read(name)) + + def test_the_root_launcher_knows_install_and_plain_start(self): + text = self.read("nerveforge") + self.assertIn('"install"', text) + self.assertIn('"uninstall"', text) + self.assertIn("from nerveforge.tunnel import main", text) + + def test_run_py_is_kept_as_an_alias(self): + text = self.read("run.py") + self.assertIn("run_module", text) + self.assertIn("nerveforge", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_static_panel.py b/tests/test_static_panel.py index 7b9e756..5dc48e0 100644 --- a/tests/test_static_panel.py +++ b/tests/test_static_panel.py @@ -351,66 +351,5 @@ class Plain(base_handler.BaseJsonHandler): handler.security_headers()["Content-Security-Policy"]) -class InstallerTests(unittest.TestCase): - def setUp(self): - self.path = ROOT / "setup_windows.ps1" - self.installer = self.path.read_text(encoding="utf-8-sig") - - def test_windows_installer_requires_explicit_dependency_opt_in(self): - self.assertTrue(self.path.read_bytes().startswith(b"\xef\xbb\xbf"), - "Windows PowerShell requires a UTF-8 BOM for Russian text") - self.assertIn("[switch]$InstallMissing", self.installer) - self.assertIn("Введите Y для подтверждения", self.installer) - self.assertIn("NERVEFORGE_WORKSPACE", self.installer) - self.assertIn("Administrator", self.installer) - self.assertIn("RUN AS ADMIN", self.installer) - self.assertIn("chr(46)", self.installer, - "Avoid PowerShell native-argument quote stripping in the Python -c probe") - - def test_windows_installer_can_install_a_tunnel_client(self): - """The old script told the operator to install cloudflared and stopped. - - That is the state the live machine was in, so the switch in the panel had - nothing to talk to. The installer now offers the package, still only - after an explicit answer. - """ - self.assertIn("[switch]$InstallTunnel", self.installer) - self.assertIn("Cloudflare.cloudflared", self.installer) - self.assertIn("Tailscale.Tailscale", self.installer) - # Nothing is installed without an answer from the operator. - for marker in ("Установите cloudflared вручную или запустите с -InstallTunnel", - "Установите Tailscale вручную или запустите с -InstallTunnel"): - self.assertIn(marker, self.installer) - - def test_windows_installer_reports_a_reason_for_every_stop(self): - """No silent exits: each failure path names what is missing or wrong.""" - for message in ("Python 3.10+ не найден", "Нужен абсолютный путь", - "Рабочая папка не выбрана", "winget.exe не найден"): - self.assertIn(message, self.installer, message) - - def test_windows_installer_blocks_are_balanced(self): - """A cheap structural check: PowerShell is not available on CI.""" - lines = self.installer.splitlines() - self.assertEqual(self.installer.count("<#"), self.installer.count("#>")) - depth = 0 - for number, line in enumerate(lines, 1): - stripped = line.strip() - if stripped.startswith("#"): - continue - quote = None - for ch in line: - if quote: - if ch == quote: - quote = None - elif ch in "\"'": - quote = ch - elif ch == "{": - depth += 1 - elif ch == "}": - depth -= 1 - self.assertGreaterEqual(depth, 0, f"unbalanced '}}' on line {number}") - self.assertEqual(depth, 0, "unbalanced braces in setup_windows.ps1") - - if __name__ == "__main__": unittest.main() From 36654a9b941176d4acd374e905d2e4186f8b7188 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:02:35 +0000 Subject: [PATCH 2/7] Fix two Windows failures the new installer tests found The .cmd wrapper did not pass on %ERRORLEVEL%, so a launcher whose Python had gone missing flashed a console and reported success. It now holds the window open on a failure and exits with the code. The read-only-directory tests assumed os.geteuid, which Windows does not have. They skip on a platform without POSIX permission bits now, and a new test refuses an unguarded os.geteuid anywhere in the installer. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- CHANGELOG.md | 10 ++- README.md | 6 +- docs/ru/CHANGELOG.md | 12 ++- docs/ru/README.md | 6 +- src/nerveforge/installer/actions.py | 6 ++ src/nerveforge/installer/apps.py | 15 +++- src/nerveforge/installer/cli.py | 3 +- tests/test_installer.py | 132 +++++++++++++++++++++++++--- 8 files changed, 164 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd4d94a..fee6f79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,11 +55,19 @@ in `nerveforge install`, where every platform gets them. `InstallerTests` used to read `setup_windows.ps1` and assert on its BOM, its `chr(46)` trick and its brace balance — tests of a script, not of an installer. -They are replaced by 64 tests that run the real steps against a temporary +They are replaced by 71 tests that run the real steps against a temporary `HOME`: an old Python fails with the reason, a relative workspace is refused, a declined download is a skip rather than a crash, running twice creates one shortcut, `--plan` creates nothing, and `--uninstall` keeps the token. +Two Windows bugs came out of writing them that way. The `.cmd` wrapper did not +pass on `%ERRORLEVEL%`, so a launcher whose Python had gone missing would flash a +console and report success; it now holds the window open on a failure and exits +with the code. And the read-only-directory tests assumed `os.geteuid`, which +Windows does not have: they now skip on a platform without POSIX permission bits +and are joined by a test that refuses an unguarded `os.geteuid` anywhere in the +installer. + ## 8.6.0 Skills stop being only the twelve that ship here. The Skills screen has a search diff --git a/README.md b/README.md index 63c799e..887bce1 100644 --- a/README.md +++ b/README.md @@ -257,11 +257,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1894 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1901 automated unit tests** (Linux, Windows, Android/Termux, API, security, tunnels). CI runs them on Linux and Windows: ```bash -python3 -m unittest discover -s tests -v # 1894 tests +python3 -m unittest discover -s tests -v # 1901 tests python3 -m compileall -q src tests run.py # Python bytecode find static -name '*.js' -print0 | xargs -0 -n1 node --check # JavaScript syntax # JS syntax bash -n setup.sh && bash -n setup_termux.sh # hand-over scripts @@ -325,7 +325,7 @@ nerveforge/ │ ├── uzhas_manager.py # Shell runner with timeout and tree cancellation │ └── workspace_manager.py # File operations, bwrap sandbox, public uploads ├── static/ # Web panel assets (HTML, CSS, JS) -├── tests/ # Unit tests (1894 tests) +├── tests/ # Unit tests (1901 tests) ├── pyproject.toml # PEP 517/518 build metadata ├── nerveforge # ./nerveforge — start, or `install` step by step ├── run.py # Alias for ./nerveforge (old shortcuts keep working) diff --git a/docs/ru/CHANGELOG.md b/docs/ru/CHANGELOG.md index 8d54583..6e09cb2 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -52,12 +52,20 @@ Windows и Termux: версия Python, права администратора, ### Тесты `InstallerTests` читали `setup_windows.ps1` и проверяли его BOM, трюк с -`chr(46)` и баланс скобок — тесты скрипта, а не установщика. Их заменили 64 -теста, которые прогоняют настоящие шаги на временном `HOME`: старый Python +`chr(46)` и баланс скобок — тесты скрипта, а не установщика. Их заменили 71 +тест, которые прогоняют настоящие шаги на временном `HOME`: старый Python падает с причиной, относительная рабочая папка отвергается, отклонённая загрузка — это пропуск, а не падение, двойной запуск создаёт один ярлык, `--plan` не создаёт ничего, а `--uninstall` сохраняет токен. +Два бага Windows всплыли именно из такого способа писать тесты. Обёртка `.cmd` +не передавала `%ERRORLEVEL%`, поэтому лаунчер, у которого пропал Python, мигал +консолью и сообщал об успехе; теперь окно остаётся открытым при ошибке, а код +возврата передаётся. А тесты на папку только для чтения опирались на +`os.geteuid`, которого в Windows нет: теперь они пропускаются на платформе без +POSIX-битов прав, и рядом появился тест, который не пропускает непроверенный +`os.geteuid` нигде в установщике. + ## 8.6.0 diff --git a/docs/ru/README.md b/docs/ru/README.md index 4aa37f9..5989f29 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -284,10 +284,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1894 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1901 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1894 unit-тестов +# Запуск 1901 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -355,7 +355,7 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1894 тестов) +├── tests/ # Набор unit-тестов (1901 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 ├── nerveforge # ./nerveforge — запуск или `install` по шагам ├── run.py # Синоним ./nerveforge (старые ярлыки работают) diff --git a/src/nerveforge/installer/actions.py b/src/nerveforge/installer/actions.py index fd9cbb7..d72d36c 100644 --- a/src/nerveforge/installer/actions.py +++ b/src/nerveforge/installer/actions.py @@ -24,6 +24,12 @@ #: Where the panel puts a downloaded cloudflared, and the installer too. One #: directory, so `--uninstall` and the panel clean up the same file. +def cloudflared_path() -> Path: + """Where a downloaded cloudflared lives — the one name, one place.""" + return bin_dir() / ("cloudflared.exe" if sys.platform.startswith("win") + else "cloudflared") + + def bin_dir() -> Path: from .. import paths diff --git a/src/nerveforge/installer/apps.py b/src/nerveforge/installer/apps.py index 07e6eda..fa1668d 100644 --- a/src/nerveforge/installer/apps.py +++ b/src/nerveforge/installer/apps.py @@ -41,9 +41,18 @@ def write_launcher(target: Path, root: Path, python: str) -> Path: target.parent.mkdir(parents=True, exist_ok=True) text = LAUNCHER.format(root=str(root).replace("\\", "/")) if target.suffix in (".exe", ".cmd", ".bat"): - # Windows will not run a shebang: wrap the Python file instead. - target.write_text(f"@echo off\r\n\"{python}\" \"%~dp0nerveforge.py\" %*\r\n", - encoding="utf-8") + # Windows will not run a shebang: wrap the Python file instead. The + # errorlevel is passed on and the window is held open on failure, so a + # broken install says so instead of flashing a console and vanishing. + target.write_text( + "@echo off\r\n" + f'"{python}" "%~dp0nerveforge.py" %*\r\n' + "if errorlevel 1 (\r\n" + " echo NerveForge stopped with an error. See docs/DEVELOPMENT.md.\r\n" + " pause\r\n" + ")\r\n" + "exit /b %errorlevel%\r\n", + encoding="utf-8") script = target.with_suffix(".py") script.write_text(text, encoding="utf-8") return target diff --git a/src/nerveforge/installer/cli.py b/src/nerveforge/installer/cli.py index 80422b0..576b493 100644 --- a/src/nerveforge/installer/cli.py +++ b/src/nerveforge/installer/cli.py @@ -186,8 +186,7 @@ def uninstall(assume_yes: bool = False) -> Report: command.skip("no launcher was installed") tunnel = report.add(Step(key="tunnel-install", title="Downloaded cloudflared")) - path = actions.bin_dir() / ("cloudflared.exe" if sys.platform.startswith("win") - else "cloudflared") + path = actions.cloudflared_path() if path.exists(): path.unlink() tunnel.done(str(path)) diff --git a/tests/test_installer.py b/tests/test_installer.py index 824a8ad..b26a0a0 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -27,6 +27,19 @@ from nerveforge.installer.steps import Outcome, Report, Step, StepContext # noqa: E402 +def _skip_if_permissions_are_not_enforced(case: unittest.TestCase) -> None: + """Read-only directory tests need a filesystem that has read-only directories. + + Windows has no ``geteuid`` at all, and on an NTFS volume ``chmod`` does not + make a folder unwritable for its owner, so the premise of the test cannot be + built there. Root on POSIX ignores the bits for the same reason. + """ + if not hasattr(os, "geteuid"): + case.skipTest("platform has no POSIX permission bits") + if os.geteuid() == 0: + case.skipTest("running as root, which can write anywhere") + + class TempHome(unittest.TestCase): """Every test gets its own HOME, so nothing touches the real one.""" @@ -170,8 +183,7 @@ def test_an_unwritable_folder_is_refused_before_the_agent_needs_it(self): blocked.mkdir() blocked.chmod(0o500) self.addCleanup(blocked.chmod, 0o700) - if os.geteuid() == 0: # root can write anywhere - self.skipTest("running as root") + _skip_if_permissions_are_not_enforced(self) step = actions.prepare_workspace(self.ctx(workspace=str(blocked)), Step("workspace", "Folder")) self.assertIs(step.outcome, Outcome.FAIL) @@ -249,6 +261,40 @@ def test_only_a_user_directory_on_path_is_chosen(self): self.assertEqual(apps.command_targets(), local / "nerveforge") +class WindowsLauncherTests(TempHome): + """The `.cmd` wrapper is the only thing a Windows user double-clicks.""" + + def write(self, target: Path) -> Path: + with mock.patch.object(apps, "command_targets", return_value=target): + step = actions.install_command( + self.ctx(command=True), Step("command", "Command")) + self.assertIs(step.outcome, Outcome.DONE) + return target + + def test_the_wrapper_keeps_the_exit_code(self): + target = self.root / "bin" / "nerveforge.cmd" + self.write(target) + text = target.read_text(encoding="utf-8") + self.assertIn("exit /b %errorlevel%", text, + "a .cmd that ends without the exit code reports success on failure") + + def test_the_wrapper_stops_before_closing_on_an_error(self): + target = self.root / "bin" / "nerveforge.cmd" + self.write(target) + text = target.read_text(encoding="utf-8") + self.assertIn("if errorlevel 1", text) + self.assertIn("pause", text) + + def test_the_python_half_is_beside_the_wrapper_and_carries_the_root(self): + target = self.root / "bin" / "nerveforge.cmd" + self.write(target) + script = target.with_suffix(".py") + self.assertTrue(script.is_file()) + text = script.read_text(encoding="utf-8") + self.assertIn("runpy.run_module", text) + self.assertIn(str(Path(__file__).resolve().parents[1]), text) + + class SelfCheckTests(TempHome): def test_the_tree_loads_and_reports_its_routes(self): step = actions.self_check(self.ctx(), Step("self-check", "Check")) @@ -297,8 +343,7 @@ def test_an_unwritable_home_is_a_named_problem_not_a_crash(self): blocked.mkdir() blocked.chmod(0o500) self.addCleanup(blocked.chmod, 0o700) - if os.geteuid() == 0: - self.skipTest("running as root") + _skip_if_permissions_are_not_enforced(self) self.assertFalse(detect.writable_directory(blocked)) @@ -348,6 +393,50 @@ def test_running_twice_does_not_create_two_of_anything(self): self.assertIsNone(second.stopped) +class PortabilityTests(TempHome): + """Windows is a first-class target, so a POSIX assumption is a bug in a test. + + The step table runs on all four platforms. `os.geteuid`, an import-time + `os.setsid`, a `chmod` used as a security boundary — each of those works on + Linux and fails on a Windows runner, and the failure arrives three minutes + later in CI instead of here. + """ + + def test_every_posix_only_os_call_is_guarded(self): + import ast + + posix_only = {"geteuid", "getuid", "setsid", "fork", "getgid"} + for path in sorted((Path(__file__).resolve().parents[1] / "src" / "nerveforge" + / "installer").glob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)): + continue + if not (isinstance(node.func.value, ast.Name) + and node.func.value.id == "os"): + continue + if node.func.attr not in posix_only: + continue + # `hasattr(os, "geteuid") and os.geteuid() == 0` is the guard. + self.assertIn("hasattr", ast.dump(tree), + f"{path.name} calls os.{node.func.attr} with no hasattr guard") + + def test_the_administrator_check_answers_on_windows_instead_of_raising(self): + # os.name == "nt" takes the ctypes branch. With no windll there — which + # is the situation on any non-Windows machine running these tests — the + # answer is False, not an exception. + fake_ctypes = mock.Mock(spec=["__name__"]) + with mock.patch("os.name", "nt"), \ + mock.patch.dict(sys.modules, {"ctypes": fake_ctypes}): + self.assertFalse(detect.admin()) + + def test_the_downloaded_binary_is_named_for_the_platform(self): + name = actions.cloudflared_path().name + self.assertEqual(name, "cloudflared.exe" if sys.platform.startswith("win") + else "cloudflared") + self.assertEqual(actions.cloudflared_path().parent, actions.bin_dir()) + + class PlanTests(TempHome): def test_the_plan_lists_the_changing_steps_and_nothing_else(self): report = cli._plan_report() @@ -424,17 +513,36 @@ def close(prompt=""): self.assertFalse(menu.ask("Install?", default=True, read=close)) + def choose(self, reply, choices, default="a"): + """Answer one choice, capturing the menu it printed. + + The menu is printed on purpose — a numbered question with no numbers is + a bug — so the test reads that output rather than leaking it into CI. + """ + printed = [] + with mock.patch("builtins.print", side_effect=lambda *a, **k: printed.append( + " ".join(str(part) for part in a))): + chosen = menu.ask_choice("Which?", choices, default=default, + read=self.answers(reply)) + return chosen, "\n".join(printed) + def test_a_choice_accepts_a_number_or_a_word(self): - read = self.answers("2") - self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("b", "B")], - default="a", read=read), "b") - read = self.answers("tailscale") - self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("tailscale", "T")], - default="a", read=read), "tailscale") + chosen, menu_text = self.choose("2", [("a", "A"), ("b", "B")]) + self.assertEqual(chosen, "b") + self.assertIn("1.", menu_text) + self.assertIn("2.", menu_text) + chosen, _ = self.choose("tailscale", [("a", "A"), ("tailscale", "T")]) + self.assertEqual(chosen, "tailscale") def test_a_nonsense_choice_takes_the_default(self): - self.assertEqual(menu.ask_choice("Which?", [("a", "A"), ("b", "B")], - default="a", read=self.answers("nonsense")), "a") + chosen, _ = self.choose("nonsense", [("a", "A"), ("b", "B")]) + self.assertEqual(chosen, "a") + + def test_the_chosen_answer_is_still_a_valid_choice(self): + for reply in ("", " ", "0", "99", "-1"): + with self.subTest(reply=reply): + chosen, _ = self.choose(reply, [("a", "A"), ("b", "B")]) + self.assertIn(chosen, ("a", "b")) class CliTests(TempHome): From 285dee15f600c3fbc2f144c56f7879f3203c6abd Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:07:09 +0000 Subject: [PATCH 3/7] Make the installer tests platform-honest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five Windows failures came from tests that assumed POSIX: a colon-separated PATH, an executable bit, a shell-script fake interpreter, a chmod that makes a folder read-only, and the local bin name. They now use os.pathsep, skip where the premise cannot exist, and assert on what Windows actually gets. One real bug fell out of it: uninstall deleted 'cloudflared' while the downloader writes 'cloudflared.exe' on Windows. Both now go through actions.cloudflared_path(), and a test checks the name matches the platform. command_targets also stopped treating any 'bin' under home as a user bin — ~/repo/src/bin was a candidate, which would drop a launcher into a build directory. Only ~/.local/bin, ~/bin and (on Windows) the WindowsApps shim count, and only when already on PATH. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- src/nerveforge/installer/apps.py | 33 ++++++++++----------- tests/test_installer.py | 50 +++++++++++++++----------------- 2 files changed, 39 insertions(+), 44 deletions(-) diff --git a/src/nerveforge/installer/apps.py b/src/nerveforge/installer/apps.py index fa1668d..7b9e342 100644 --- a/src/nerveforge/installer/apps.py +++ b/src/nerveforge/installer/apps.py @@ -70,31 +70,30 @@ def make_executable(path: Path) -> None: def command_targets() -> Path | None: """The first per-user directory on `PATH` where a `nerveforge` command belongs. - Only a directory that already exists and belongs to this user is chosen. The - alternative — creating one and editing `~/.bashrc` — is how installers break - shells, and this one will not do it. + "Belongs to this user" is a short list, not "anywhere under home": a folder + called `bin` inside a project is `~/repo/src/bin`, and dropping a launcher in + a project's build output is a surprise, not an install. Only the conventional + per-user directories count, and only if they are already on `PATH` — editing + a shell profile is how installers break shells, and this one will not do it. """ import os name = "nerveforge.exe" if os.name == "nt" else "nerveforge" home = Path.home() - on_path = [Path(entry) for entry in os.environ.get("PATH", "").split(os.pathsep) if entry] - for candidate in on_path: + candidates = [home / ".local" / "bin", home / "bin"] + if os.name == "nt": + # %LOCALAPPDATA%\Microsoft\WindowsApps is the per-user shim folder. + local = os.environ.get("LOCALAPPDATA") + if local: + candidates.insert(0, Path(local) / "Microsoft" / "WindowsApps") + on_path = {path.expanduser() for path in + (Path(entry) for entry in os.environ.get("PATH", "").split(os.pathsep) if entry)} + for candidate in candidates: try: - resolved = candidate.expanduser() - if not resolved.is_dir(): - continue - # Refuse system directories: writing there needs root and surprises - # whoever looks after the machine. - if home not in resolved.parents and resolved != home / ".local" / "bin": - continue - if resolved.name in ("bin", "sbin") and home in resolved.parents: - return resolved / name + if candidate in on_path and candidate.is_dir(): + return candidate / name except OSError: continue - local_bin = home / ".local" / "bin" - if local_bin in [path.expanduser() for path in on_path] and local_bin.is_dir(): - return local_bin / name return None diff --git a/tests/test_installer.py b/tests/test_installer.py index b26a0a0..50b9c5a 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -27,19 +27,6 @@ from nerveforge.installer.steps import Outcome, Report, Step, StepContext # noqa: E402 -def _skip_if_permissions_are_not_enforced(case: unittest.TestCase) -> None: - """Read-only directory tests need a filesystem that has read-only directories. - - Windows has no ``geteuid`` at all, and on an NTFS volume ``chmod`` does not - make a folder unwritable for its owner, so the premise of the test cannot be - built there. Root on POSIX ignores the bits for the same reason. - """ - if not hasattr(os, "geteuid"): - case.skipTest("platform has no POSIX permission bits") - if os.geteuid() == 0: - case.skipTest("running as root, which can write anywhere") - - class TempHome(unittest.TestCase): """Every test gets its own HOME, so nothing touches the real one.""" @@ -80,6 +67,8 @@ def test_an_unreadable_interpreter_is_not_called_supported(self): self.assertFalse(detect._probe_python("/nonexistent/python").supported) def test_a_fake_interpreter_is_probed_by_running_it(self): + if sys.platform.startswith("win"): + self.skipTest("the fake interpreter is a POSIX shell script") fake = self.root / "python3.9" fake.write_text("#!/bin/sh\necho 3.9.1\n", encoding="utf-8") fake.chmod(0o755) @@ -179,13 +168,13 @@ def test_a_relative_path_is_refused_with_the_reason(self): self.assertIn("--workspace", step.remedy) def test_an_unwritable_folder_is_refused_before_the_agent_needs_it(self): + # A mock rather than chmod: "writable" is not a property NTFS lets its + # owner take away, so a chmod-based test cannot exist on Windows. blocked = self.root / "blocked" blocked.mkdir() - blocked.chmod(0o500) - self.addCleanup(blocked.chmod, 0o700) - _skip_if_permissions_are_not_enforced(self) - step = actions.prepare_workspace(self.ctx(workspace=str(blocked)), - Step("workspace", "Folder")) + with mock.patch.object(detect, "writable_directory", return_value=False): + step = actions.prepare_workspace(self.ctx(workspace=str(blocked)), + Step("workspace", "Folder")) self.assertIs(step.outcome, Outcome.FAIL) self.assertIn("cannot be written", step.detail) @@ -247,17 +236,21 @@ def test_a_launcher_is_a_python_file_with_an_absolute_root(self): self.assertIs(step.outcome, Outcome.DONE) text = target.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - self.assertIn(str(Path(__file__).resolve().parents[1]), text) + self.assertIn(str(Path(__file__).resolve().parents[1]).replace("\\", "/"), text) if not sys.platform.startswith("win"): self.assertTrue(os.access(target, os.X_OK)) def test_only_a_user_directory_on_path_is_chosen(self): - with mock.patch.dict(os.environ, {"PATH": "/usr/bin:/bin"}), \ + local = self.root / ".local" / "bin" + system = self.root / "usr" / "bin" + system.mkdir(parents=True) + with mock.patch.dict(os.environ, {"PATH": str(system)}), \ mock.patch.object(Path, "home", return_value=self.root): self.assertIsNone(apps.command_targets()) - local = self.root / ".local" / "bin" local.mkdir(parents=True) - with mock.patch.dict(os.environ, {"PATH": f"/usr/bin:{local}"}): + on_path = os.pathsep.join([str(system), str(local)]) + with mock.patch.dict(os.environ, {"PATH": on_path}), \ + mock.patch.object(Path, "home", return_value=self.root): self.assertEqual(apps.command_targets(), local / "nerveforge") @@ -337,14 +330,13 @@ def test_termux_is_detected_by_its_own_marker_not_by_android(self): with mock.patch.dict(os.environ, {"PREFIX": "/usr"}, clear=False): self.assertFalse(detect.is_termux()) - def test_an_unwritable_home_is_a_named_problem_not_a_crash(self): + def test_an_unwritable_directory_answers_false_instead_of_raising(self): self.assertTrue(detect.writable_directory(self.root)) blocked = self.root / "readonly" blocked.mkdir() - blocked.chmod(0o500) - self.addCleanup(blocked.chmod, 0o700) - _skip_if_permissions_are_not_enforced(self) - self.assertFalse(detect.writable_directory(blocked)) + with mock.patch.object(Path, "mkdir", side_effect=PermissionError("denied")), \ + mock.patch("builtins.open", side_effect=PermissionError("denied")): + self.assertFalse(detect.writable_directory(blocked)) class RunTests(TempHome): @@ -621,8 +613,12 @@ def test_a_downloaded_cloudflared_is_removed(self): binary.parent.mkdir(parents=True) binary.write_bytes(b"#!/bin/sh\n") + # The name the uninstaller deletes must be the name the downloader + # writes: .exe on Windows, bare here. with mock.patch.object(apps, "command_targets", return_value=None), \ mock.patch.object(actions, "bin_dir", return_value=self.root / "bin"), \ + mock.patch.object(actions, "cloudflared_path", + return_value=binary), \ mock.patch("builtins.print"): report = cli.uninstall() self.assertFalse(binary.exists()) From da867b73315ac3b55df7b503678076faf7a1b0ef Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:11:16 +0000 Subject: [PATCH 4/7] Compare paths the way Windows reports them Three failures left: the launcher and desktop-entry tests built expected paths with str(), which is backslashes on Windows and slashes everywhere else, and the PATH test expected a bare launcher name on a platform that names it .exe. Written with as_posix() and os.name now. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- tests/test_installer.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/test_installer.py b/tests/test_installer.py index 50b9c5a..8314c2d 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -215,8 +215,11 @@ def test_a_desktop_entry_is_written_when_asked_on_a_desktop(self): self.assertIn("Terminal=true", text) def test_the_desktop_entry_quotes_paths_with_spaces(self): - entry = apps.desktop_entry(Path("/opt/my apps/Neuro"), "/usr/bin/python3") - self.assertIn('"/opt/my apps/Neuro/run.py"', entry) + root = Path("/opt/my apps/Neuro") + entry = apps.desktop_entry(root, "/usr/bin/python3") + self.assertIn((root / "run.py").as_posix(), entry) + exec_line = next(line for line in entry.splitlines() if line.startswith("Exec=")) + self.assertEqual(exec_line.count('"'), 4, exec_line) def test_a_desktop_entry_without_an_icon_does_not_invent_one(self): entry = apps.desktop_entry(self.root, "/usr/bin/python3") @@ -236,7 +239,8 @@ def test_a_launcher_is_a_python_file_with_an_absolute_root(self): self.assertIs(step.outcome, Outcome.DONE) text = target.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - self.assertIn(str(Path(__file__).resolve().parents[1]).replace("\\", "/"), text) + expected = Path(__file__).resolve().parents[1].as_posix() + self.assertIn(expected, text.replace("\\", "/")) if not sys.platform.startswith("win"): self.assertTrue(os.access(target, os.X_OK)) @@ -249,9 +253,10 @@ def test_only_a_user_directory_on_path_is_chosen(self): self.assertIsNone(apps.command_targets()) local.mkdir(parents=True) on_path = os.pathsep.join([str(system), str(local)]) + expected = local / ("nerveforge.exe" if os.name == "nt" else "nerveforge") with mock.patch.dict(os.environ, {"PATH": on_path}), \ mock.patch.object(Path, "home", return_value=self.root): - self.assertEqual(apps.command_targets(), local / "nerveforge") + self.assertEqual(apps.command_targets(), expected) class WindowsLauncherTests(TempHome): From 609761b2674445a4eaf8c14835c89b639e354a34 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:14:30 +0000 Subject: [PATCH 5/7] Write the desktop entry with the separators it is read with The .desktop file is Linux-only, but two tests compared its paths with str() and as_posix(), which differ on Windows. The entry now writes forward slashes by construction, and the tests compare the same repr the launcher contains. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- src/nerveforge/installer/apps.py | 4 ++-- tests/test_installer.py | 11 ++++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/nerveforge/installer/apps.py b/src/nerveforge/installer/apps.py index 7b9e342..8cae114 100644 --- a/src/nerveforge/installer/apps.py +++ b/src/nerveforge/installer/apps.py @@ -114,8 +114,8 @@ def desktop_entry(root: Path, python: str) -> str: "Type=Application\n" "Name=NerveForge\n" "Comment=Start the bridge and its tunnel (Cloudflare or Tailscale)\n" - f"Exec={desktop_quote(python)} {desktop_quote(str(root / 'run.py'))}\n" - f"Path={root}\n" + f"Exec={desktop_quote(python)} {desktop_quote((root / 'run.py').as_posix())}\n" + f"Path={root.as_posix()}\n" + (f"Icon={icon}\n" if icon.is_file() else "") + "Terminal=true\n" "Categories=Network;Utility;\n" diff --git a/tests/test_installer.py b/tests/test_installer.py index 8314c2d..922ebb4 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -217,7 +217,10 @@ def test_a_desktop_entry_is_written_when_asked_on_a_desktop(self): def test_the_desktop_entry_quotes_paths_with_spaces(self): root = Path("/opt/my apps/Neuro") entry = apps.desktop_entry(root, "/usr/bin/python3") - self.assertIn((root / "run.py").as_posix(), entry) + # The entry is a Linux file, so the path inside it is written with + # forward slashes whatever produced it — a backslash is an escape in a + # .desktop Exec line, not a separator. + self.assertIn("/opt/my apps/Neuro/run.py", entry) exec_line = next(line for line in entry.splitlines() if line.startswith("Exec=")) self.assertEqual(exec_line.count('"'), 4, exec_line) @@ -239,8 +242,10 @@ def test_a_launcher_is_a_python_file_with_an_absolute_root(self): self.assertIs(step.outcome, Outcome.DONE) text = target.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - expected = Path(__file__).resolve().parents[1].as_posix() - self.assertIn(expected, text.replace("\\", "/")) + # A Python repr of the root, compared as the same repr — str() and + # as_posix() disagree about the separator on Windows. + root = Path(__file__).resolve().parents[1] + self.assertIn(f"ROOT = {str(root)!r}", text) if not sys.platform.startswith("win"): self.assertTrue(os.access(target, os.X_OK)) From f1ad5267e686431cfa81bfc47daa4eebbe3a9172 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:17:49 +0000 Subject: [PATCH 6/7] Look for the launcher where the platform writes it On Windows command_targets returns nerveforge.exe and the Python half sits beside it as nerveforge.py; the test read the bare 'nerveforge' path, which is the POSIX layout only. Both launcher tests now resolve the file the way install_command does. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- tests/test_installer.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_installer.py b/tests/test_installer.py index 922ebb4..968496a 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -236,11 +236,16 @@ def test_putting_a_launcher_on_path_needs_a_yes(self): self.assertIn("--command", step.detail) def test_a_launcher_is_a_python_file_with_an_absolute_root(self): - target = self.root / ".local" / "bin" / "nerveforge" + target = self.root / ".local" / "bin" / ( + "nerveforge.exe" if sys.platform.startswith("win") else "nerveforge") with mock.patch.object(apps, "command_targets", return_value=target): step = actions.install_command(self.ctx(command=True), Step("command", "Command")) self.assertIs(step.outcome, Outcome.DONE) - text = target.read_text(encoding="utf-8") + # On Windows the thing a person runs is the .cmd shim and the Python + # half sits beside it; elsewhere the launcher itself is the Python file. + script = target.with_suffix(".py") if target.suffix else target + self.assertTrue(script.is_file(), f"{script} was not written") + text = script.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) # A Python repr of the root, compared as the same repr — str() and # as_posix() disagree about the separator on Windows. @@ -295,7 +300,7 @@ def test_the_python_half_is_beside_the_wrapper_and_carries_the_root(self): self.assertTrue(script.is_file()) text = script.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - self.assertIn(str(Path(__file__).resolve().parents[1]), text) + self.assertIn(f"ROOT = {str(Path(__file__).resolve().parents[1])!r}", text) class SelfCheckTests(TempHome): From 6317518811b4cbe48283fcbac3b2a763320dc998 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:21:20 +0000 Subject: [PATCH 7/7] Compare the launcher root as a path, not as a string The launcher writes forward slashes on every platform, so a Windows runner reads back D:/a/... while str(Path) there is D:\\a\\.... The tests now parse the ROOT line and compare it with the tree as paths, which is what the launcher itself relies on. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- tests/test_installer.py | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/tests/test_installer.py b/tests/test_installer.py index 968496a..4c8ab23 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -27,6 +27,31 @@ from nerveforge.installer.steps import Outcome, Report, Step, StepContext # noqa: E402 +def _launcher_root(text: str) -> str | None: + """The root a generated launcher points at, parsed back out of the file.""" + import ast + + for line in text.splitlines(): + if line.startswith("ROOT = "): + try: + value = ast.literal_eval(line[len("ROOT = "):]) + except (SyntaxError, ValueError): + return None + return value if isinstance(value, str) else None + return None + + +def _same_path(written: str, expected: Path) -> bool: + """Compare a launcher's root with the tree, whatever separators it used. + + The launcher writes forward slashes on every platform; a Windows runner + reads D:/a/... back while str(Path) there is D:\\a\\..., so the two are + compared as paths rather than as strings. + """ + normalised = written.rstrip("/\\").replace("\\", "/") + return normalised == expected.as_posix().rstrip("/\\") + + class TempHome(unittest.TestCase): """Every test gets its own HOME, so nothing touches the real one.""" @@ -247,10 +272,9 @@ def test_a_launcher_is_a_python_file_with_an_absolute_root(self): self.assertTrue(script.is_file(), f"{script} was not written") text = script.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - # A Python repr of the root, compared as the same repr — str() and - # as_posix() disagree about the separator on Windows. - root = Path(__file__).resolve().parents[1] - self.assertIn(f"ROOT = {str(root)!r}", text) + written = _launcher_root(text) + self.assertIsNotNone(written, text) + self.assertTrue(_same_path(written, Path(__file__).resolve().parents[1]), written) if not sys.platform.startswith("win"): self.assertTrue(os.access(target, os.X_OK)) @@ -300,7 +324,9 @@ def test_the_python_half_is_beside_the_wrapper_and_carries_the_root(self): self.assertTrue(script.is_file()) text = script.read_text(encoding="utf-8") self.assertIn("runpy.run_module", text) - self.assertIn(f"ROOT = {str(Path(__file__).resolve().parents[1])!r}", text) + written = _launcher_root(text) + self.assertIsNotNone(written, text) + self.assertTrue(_same_path(written, Path(__file__).resolve().parents[1]), written) class SelfCheckTests(TempHome):