aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/tests
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-09-04 17:29:24 +0200
committerChristophe Besson <cbesson@gmail.com>2026-09-04 17:29:24 +0200
commitb78288640d8c13cc0fb3f4ee7c82f3efac33940f (patch)
treef860bd35f2efd8b6781e8e279ee75389b5a06128 /packages/meshbay-node/tests
parent13d145253a871ef47ef4344f90566eea21b994ab (diff)
downloadmeshbay-b78288640d8c13cc0fb3f4ee7c82f3efac33940f.tar.gz
feat: opt-in Windows service mode (boot-time, one elevation) + v1.0.0
The per-user Startup-folder launcher (W3) only ever runs after this user signs in. A real Windows Service would start earlier, but under LocalSystem/NetworkService -- accounts with no normal profile, so %LOCALAPPDATA%\meshbay\ (config, keystore, data) would not exist for it. Relocating storage to make that work is real surgery, deliberately not done here. Instead: a Scheduled Task, created once with admin rights, that runs AS THIS USER at boot without needing them to sign in first. `schtasks /create ... /ru <user> /rp ""` with no `/it` registers an S4U (Service For User) logon -- no password stored anywhere, and unlike LocalSystem it loads this account's own profile, so config_dir()/ data_dir() need zero changes. The cost: S4U carries no network credential, which the node never needed -- everything it touches is local disk plus outbound internet. Creating the task needs admin (a boot trigger touches system-wide scheduler state, the same reason /sc onlogon needed it); querying/starting/stopping an existing one does not -- Task Scheduler grants the owning user that much itself, which is what lets the Node page's Start/Stop/Restart drive it with no further UAC prompts. meshbay_node/platform.py service_install/_remove/_status/_run/_end -- mirrors autostart_* but for the Scheduled Task; TASK_NAME moved here (was decorative before) meshbay_node/daemon.py new `service install|remove|start|stop|status` verb; restart-daemon and reset now check for the service task too packaging/win/service.ps1 the installer-side equivalent (extraResource); status/run/end never self-elevate -- only install/remove do, exactly matching what Task Scheduler itself requires packaging/win/service-mode.ps1 ONE elevated helper running service.ps1 + firewall.ps1 together, so choosing service mode costs exactly one UAC prompt, not two build/installer.nsh the install-time choice: "run as a background service?" (one elevation, both jobs) vs the existing per-user + separate firewall question. Checked first, unelevated, so re-running setup with everything already configured asks nothing. Uninstall offers the matching one-elevation cleanup, default No. src/main.js winServiceTaskStatus/Run/End, wired into node:installed, node:service-status/-stop/-restart and node:start: when the Scheduled Task exists, drive it; otherwise fall back to the existing per-user spawn/kill path. This is the hard requirement -- Start/Stop/Restart from the Node page must work in either mode. node-page.js / locales a hint explaining why the per-user autostart toggle is absent when service mode is active (info.mode from the backend, no new field to gate on -- it just isn't sent in that case) package.json: 0.1.0 -> 1.0.0. Verified: electron-builder compiles the new NSIS choice logic and ships all three scripts; service.ps1's S4U install fails cleanly (Access denied) when run unelevated, and its status/run/end never touch "runas". Cannot verify the elevated success path myself (no admin in this session) -- that needs a real UAC click. Node suite 843 pass / 25 skip; test_packaging_win.py pins the one-elevation property, the S4U flags, and that main.js actually checks the service task in all three handlers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'packages/meshbay-node/tests')
-rw-r--r--packages/meshbay-node/tests/test_cli_dispatch.py1
-rw-r--r--packages/meshbay-node/tests/test_packaging_win.py141
2 files changed, 121 insertions, 21 deletions
diff --git a/packages/meshbay-node/tests/test_cli_dispatch.py b/packages/meshbay-node/tests/test_cli_dispatch.py
index 606e586..caf672d 100644
--- a/packages/meshbay-node/tests/test_cli_dispatch.py
+++ b/packages/meshbay-node/tests/test_cli_dispatch.py
@@ -43,6 +43,7 @@ VERBS = [
["reload"],
["restart-daemon"],
["autostart", "status"],
+ ["service", "status"],
]
diff --git a/packages/meshbay-node/tests/test_packaging_win.py b/packages/meshbay-node/tests/test_packaging_win.py
index 20a2505..6471446 100644
--- a/packages/meshbay-node/tests/test_packaging_win.py
+++ b/packages/meshbay-node/tests/test_packaging_win.py
@@ -182,50 +182,149 @@ def _macro_body(nsh: str, name: str) -> str:
return nsh.split(f"!macro {name}", 1)[1].split("!macroend", 1)[0]
-def test_the_installer_offers_one_elevated_firewall_step_instead_of_two_dialogs():
+def test_the_installer_offers_a_service_mode_choice_with_one_elevation():
"""
- Adding a firewall rule needs admin; the install itself never elevates
- (build.nsis allowElevation:false). So this must be opt-in (a Yes/No the
- user can decline) and skipped entirely in a silent install — an
- unattended `/S` install must never pop a UAC prompt on its own.
+ Adding a firewall rule or a boot-time Scheduled Task both need admin; the
+ install itself never elevates (build.nsis allowElevation:false). So this
+ must be opt-in (a Yes/No the user can decline) and skipped entirely in a
+ silent install — an unattended `/S` install must never pop a UAC prompt on
+ its own. Choosing service mode must fold the Scheduled Task AND the
+ firewall rules into ONE elevation (service-mode.ps1), never two.
"""
nsh = NSH.read_text(encoding="utf-8")
install = _macro_body(nsh, "customInstall")
assert "${IfNot} ${Silent}" in install, (
- "the firewall step is not guarded against silent installs")
- assert 'MessageBox MB_YESNO' in install
+ "the mode choice is not guarded against silent installs")
+ assert install.count("MessageBox MB_YESNO") == 2, (
+ "expected exactly two questions: service-mode-or-not, then (only in "
+ "the per-user branch) the firewall-only question")
assert 'ExecShellWait "runas"' in install
- assert 'firewall.ps1" add' in install
+ # Service mode: one elevated call for both jobs, not one each.
+ assert 'service-mode.ps1" -Action install' in install
+ assert 'firewall.ps1" add' not in install.split("mb_peruser_mode:", 1)[0], (
+ "service mode must not ALSO separately elevate for firewall.ps1 — "
+ "service-mode.ps1 already does that in the same elevation")
+ # Per-user mode (declined the service question) keeps today's separate,
+ # still-opt-in firewall step.
+ peruser_branch = install.split("mb_peruser_mode:", 1)[1]
+ assert 'firewall.ps1" add' in peruser_branch
-def test_reinstalling_with_the_rules_already_in_place_asks_nothing():
+def test_reinstalling_with_everything_already_in_place_asks_nothing():
"""
Get-NetFirewallRule needs no admin, only New/Remove do — so customInstall
- checks first, unelevated, and only reaches the MessageBox (and therefore
- the UAC prompt) when something is actually missing. Without this, running
- setup a second time — an upgrade, a repair install — would re-ask the
- question and re-trigger UAC even though nothing needs to change.
+ checks the firewall rules first, unelevated, and only reaches the mode
+ question (and therefore a possible UAC prompt) when something is actually
+ missing. Without this, running setup a second time — an upgrade, a repair
+ install — would re-ask the question (and, in service mode, re-trigger UAC)
+ even though nothing needs to change. Checking the firewall rules alone is
+ enough: service-mode.ps1 always sets up both together, so if the rules
+ are there, so is everything else that was chosen last time.
"""
nsh = NSH.read_text(encoding="utf-8")
install = _macro_body(nsh, "customInstall")
check_line = 'firewall.ps1" check'
assert check_line in install
- # The check must run, and be evaluated, before the MessageBox — not after.
- assert install.index(check_line) < install.index("MessageBox MB_YESNO")
- assert "Pop $0" in install and "${If} $0 != 0" in install
+ mode_question = "Run MeshBay Node as a background service?"
+ # The check must run, and be evaluated, before the mode question — not after.
+ assert install.index(check_line) < install.index(mode_question)
+ assert "Pop $0" in install and "${If} $0 == 0" in install
+ assert "Goto mb_mode_done" in install
-def test_the_uninstaller_offers_to_remove_the_firewall_rules_default_no():
- """Opt-in on the way out too, and defaulting to No: a stale allow-rule
- for a deleted exe is inert, so this should not nag."""
+def test_the_uninstaller_offers_to_remove_everything_privileged_default_no():
+ """
+ Opt-in on the way out too, and defaulting to No: a stale allow-rule or
+ Scheduled Task is inert, so this should not nag. One elevation removes
+ both, unconditionally — service-mode.ps1's own remove actions are each
+ no-ops when there is nothing to remove, so this is safe to run whether or
+ not service mode was ever chosen.
+ """
nsh = NSH.read_text(encoding="utf-8")
uninstall = _macro_body(nsh, "customUnInstall")
assert "${IfNot} ${Silent}" in uninstall
- assert "/SD IDNO" in uninstall, "the uninstall firewall prompt should default to No"
- assert 'firewall.ps1" remove' in uninstall
+ assert "/SD IDNO" in uninstall, "the uninstall prompt should default to No"
+ assert 'service-mode.ps1" -Action remove' in uninstall
+ assert 'ExecShellWait "runas"' in uninstall
+
+
+# ── service mode itself (packaging/win/service.ps1, service-mode.ps1) ──────
+
+def test_service_ps1_and_service_mode_ps1_are_extraresources():
+ for name in ("service.ps1", "service-mode.ps1"):
+ entry = next(
+ (e for e in _pkg()["build"]["win"]["extraResources"] if e.get("to") == name),
+ None)
+ assert entry, f"no extraResources entry mapping to {name}"
+ assert entry["from"].endswith(f"packaging/win/{name}")
+ assert (WIN / name).exists()
+
+
+def test_service_install_uses_s4u_not_a_stored_password():
+ """
+ schtasks /create ... /ru <user> /rp "" with no /it registers an S4U logon:
+ no password stored anywhere, and — unlike LocalSystem/NetworkService — it
+ loads this account's own profile, so %LOCALAPPDATA%\\meshbay\\ needs no
+ relocation. Losing the empty /rp "" (e.g. "fixing" it into a real prompt
+ for a password) would either store a secret or silently stop working.
+ """
+ src = (WIN / "service.ps1").read_text(encoding="utf-8")
+ # The prose above the actual command is allowed to say "/it" while
+ # explaining why it is absent (the same "read the comment, not the
+ # directive" trap CLAUDE.md already tracks) -- so check the real
+ # invocation line, not the whole file.
+ create_line = next(
+ (line for line in src.splitlines() if line.strip().startswith("& schtasks")
+ and "/create" in line), None)
+ assert create_line, "no schtasks /create invocation found"
+ tokens = create_line.split()
+ assert "/sc" in tokens and tokens[tokens.index("/sc") + 1] == "onstart", (
+ "must trigger at boot, not at sign-in (/sc onlogon)")
+ assert "/ru" in tokens
+ assert "/rp" in tokens and tokens[tokens.index("/rp") + 1] == '""', (
+ "must pass an empty run-as password (S4U)")
+ assert "/it" not in tokens, "an interactive-token task would need the user signed in"
+ assert "Get-Credential" not in src, "no password should ever be prompted for"
+
+
+def test_service_task_name_is_the_same_everywhere():
+ """One name, three places: meshbay_node.platform.TASK_NAME (the CLI),
+ service.ps1 (the installer), and main.js's WIN_SERVICE_TASK (the client
+ driving Start/Stop/Restart). A mismatch means the client manages a task
+ that does not exist, or vice versa."""
+ from meshbay_node import platform as plat
+
+ service_ps1 = (WIN / "service.ps1").read_text(encoding="utf-8")
+ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
+
+ assert f'$TASK_NAME = "{plat.TASK_NAME}"' in service_ps1
+ assert f"WIN_SERVICE_TASK = '{plat.TASK_NAME}'" in main_js
+
+
+def test_service_status_reports_state_without_admin():
+ """status/run/end must not need elevation once the task exists (only
+ install/remove do) — that is what lets the Node page drive it with no
+ further UAC prompts. Nothing in those branches should invoke as an
+ elevated call; only the two macros in installer.nsh use "runas"."""
+ src = (WIN / "service.ps1").read_text(encoding="utf-8")
+ assert "runas" not in src.lower(), (
+ "service.ps1 itself must never self-elevate — installer.nsh already "
+ "runs the whole script elevated for install/remove, and the client "
+ "calls status/run/end directly, unelevated")
+
+
+def test_main_js_drives_the_service_task_for_all_three_actions():
+ """The hard requirement: Start/Stop/Restart from the Node page must
+ control the Scheduled Task when service mode is active, not just spawn a
+ detached process that has nothing to do with it."""
+ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8")
+ for handler in ("node:service-stop", "node:service-restart", "node:start"):
+ body = main_js.split(f"ipcMain.handle('{handler}'", 1)[1]
+ body = body[:body.index("ipcMain.handle(")]
+ assert "winServiceTaskStatus" in body, f"{handler} never checks for the service task"
def test_firewall_ps1_targets_both_executables_and_is_idempotent():