""" The Windows installer (W4): a single per-user NSIS package carrying the Electron client and the frozen node daemon. Like test_packaging_units.py this reads the config rather than building anything — there is no electron-builder or PyInstaller run here. Weak evidence, and the right kind for the defects it guards against: a per-machine flag that would make the installer demand admin, a build step wired to the wrong file, the 150 MB node-runtime artifact slipping into git, the autostart seam between the NSIS uninstaller and meshbay_node.platform drifting apart. """ import json import re from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[3] CLIENT = ROOT / "packages" / "meshbay-client" PKG_JSON = CLIENT / "package.json" WIN = ROOT / "packaging" / "win" NSH = CLIENT / "build" / "installer.nsh" MAIN_JS = CLIENT / "src" / "main.js" PRELOAD_JS = CLIENT / "src" / "preload.js" # The "Light" target: Electron client + UI, no bundled node. See # C:\Users\admin\devel\light-client.md for the evaluation this implements. LIGHT_NSH = CLIENT / "build" / "installer-light.nsh" LIGHT_YML = WIN / "electron-builder.light.yml" BUILD_WIN_LIGHT = WIN / "build-win-light.ps1" BUILD_WIN_COMMON = WIN / "build-win-common.ps1" # The "MSIX" target: same feature set as Full, packaged for Microsoft Store # submission instead of NSIS. See C:\Users\admin\devel\msix-installer.md for # the plan this implements. MSIX_YML = WIN / "electron-builder.msix.yml" BUILD_WIN_MSIX = WIN / "build-win-msix.ps1" MSIX_EXTENSIONS_XML = CLIENT / "build" / "appx-extensions.xml" # sync-ui.js copies this into CLIENT/ui/ verbatim -- read the source of # truth, same as every other cross-package check in this file already does # for meshbay-client's own src/. HUB_STATIC = ROOT / "packages" / "meshbay-hub" / "src" / "meshbay_hub" / "static" pytestmark = pytest.mark.skipif( not PKG_JSON.exists() or not WIN.exists(), reason="Windows packaging not present") def _pkg() -> dict: return json.loads(PKG_JSON.read_text(encoding="utf-8")) # ── electron-builder: Windows target ──────────────────────────────────────── def test_the_windows_target_is_nsis_with_the_committed_icon(): win = _pkg()["build"]["win"] assert win["target"] == "nsis" icon = CLIENT / win["icon"] assert icon.suffix == ".ico" and icon.exists(), f"{icon} is missing" def test_the_installer_is_per_user_and_never_asks_for_admin(): """ A logon-triggered scheduled task needs elevation (that is why W3 uses the Startup folder), and the whole desktop design is no-admin. perMachine or allowElevation here would undo that at install time. """ nsis = _pkg()["build"]["nsis"] assert nsis["oneClick"] is False assert nsis["perMachine"] is False assert nsis["allowElevation"] is False assert nsis["allowToChangeInstallationDirectory"] is True def test_the_node_runtime_is_carried_as_an_extraresource(): """ PyInstaller output lands in packages/meshbay-client/node-runtime/ and rides into the package under resources/node-runtime/. src/main.js:findNodeBinary resolves exactly that path (process.resourcesPath / node-runtime / meshbay-node.exe), so the two names must agree. """ extra = _pkg()["build"]["win"]["extraResources"] entry = next((e for e in extra if e.get("to") == "node-runtime"), None) assert entry, "no extraResources entry mapping to node-runtime" assert entry["from"] == "node-runtime" main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8") assert "'node-runtime', 'meshbay-node.exe'" in main_js, ( "findNodeBinary no longer looks for the bundled daemon where " "extraResources puts it") def test_find_node_binary_strips_stray_cr_from_multiline_where_output(): """ where.exe/which can list more than one match on PATH, and each line keeps its own trailing \\r on Windows. `stdout.trim().split('\\n')[0]` only strips the ends of the *whole* string, so with 2+ matches a stray \\r stayed glued to the end of the first line -- which then landed inside the quoted path written into the Startup .vbs and broke VBScript's parser with "Unterminated string constant" the next time Windows ran it at sign-in. Reproduced live 2026-09-05 (this user's own machine has both a dev venv and an installed build on PATH) and fixed by splitting on \\r?\\n and trimming each candidate line individually. """ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8") assert "stdout.split(/\\r?\\n/)" in main_js, ( "findNodeBinary must split where.exe/which output on \\r?\\n and " "trim each line, not a single stdout.trim() over the whole blob") assert "stdout.trim().split('\\n')[0]" not in main_js def test_firewall_helper_is_carried_as_an_extraresource(): """packaging/win/firewall.ps1 must ride into resources/, at the fixed path installer.nsh invokes it from ($INSTDIR\\resources\\firewall.ps1).""" extra = _pkg()["build"]["win"]["extraResources"] entry = next((e for e in extra if e.get("to") == "firewall.ps1"), None) assert entry, "no extraResources entry mapping to firewall.ps1" assert entry["from"].endswith("packaging/win/firewall.ps1") assert (ROOT / "packaging" / "win" / "firewall.ps1").exists() def test_dist_win_delegates_to_the_build_script(): """`dist` (Linux) delegates to build-client.sh; `dist:win` is its counterpart and must not be a second inline electron-builder invocation.""" scripts = _pkg()["scripts"] assert "dist:win" in scripts assert "build-win.ps1" in scripts["dist:win"] # `dist` stays Linux-only and unchanged (test_desktop_shell.py guards it too). assert "win" not in scripts["dist"].lower() # ── the build scripts exist and point at real files ──────────────────────── @pytest.mark.parametrize("name", [ "build-win.ps1", "build-node-runtime.ps1", "meshbay-node.spec", "node-entry.py", "README.md", ]) def test_packaging_win_ships_its_scripts(name): assert (WIN / name).exists(), f"packaging/win/{name} is missing" def test_the_pyinstaller_entry_point_is_the_daemon_main(): src = (WIN / "node-entry.py").read_text(encoding="utf-8") assert "from meshbay_node.daemon import main" in src assert "main()" in src def test_the_spec_pulls_in_the_awkward_dependencies_whole(): """ The C/Rust-extension and dynamic-import packages are the ones PyInstaller's static pass drops. If someone trims collect_all to shrink the build, the frozen daemon fails at runtime, not at build time. """ spec = (WIN / "meshbay-node.spec").read_text(encoding="utf-8") for pkg in ("aiortc", "av", "aioquic", "pydantic_core", "uvicorn", "watchdog", "guessit", "blake3", "meshbay_node", "meshbay_common"): assert re.search(rf'["\']{re.escape(pkg)}["\']', spec), ( f"{pkg} dropped from the PyInstaller spec's collect list") def test_the_frozen_exe_carries_a_version_resource(): """ Without it the Windows Firewall prompt, Task Manager and Properties show a bare "meshbay-node". The version is read from the installed package so it tracks pyproject rather than being a second copy to update. """ spec = (WIN / "meshbay-node.spec").read_text(encoding="utf-8") assert "VSVersionInfo" in spec assert "version=_version_info" in spec, "EXE() is not given the version resource" assert 'StringStruct("ProductName", "MeshBay Node")' in spec assert '_pkg_version("meshbay-node")' in spec, "version is hardcoded, not read from the package" # ── the artifact never gets committed ────────────────────────────────────── def test_the_node_runtime_output_is_gitignored(): """It is ~150 MB of frozen Python. The `ui/` fork guard in test_desktop_shell.py exists for the same reason.""" gitignore = (ROOT / ".gitignore").read_text(encoding="utf-8") assert "packages/meshbay-client/node-runtime/" in gitignore # ── the NSIS ↔ platform.py autostart seam ───────────────────────────────── def test_the_uninstaller_clears_the_autostart_launcher(): """ W3's `meshbay-node autostart install` drops a .vbs in the Startup folder (meshbay_node.platform._startup_vbs). After an uninstall it would point wscript at a deleted binary every sign-in, so customUnInstall must delete it — and at the path platform.py actually uses. """ from meshbay_node import platform as plat nsh = NSH.read_text(encoding="utf-8") assert "!macro customUnInstall" in nsh assert "taskkill /IM meshbay-node.exe /F" in nsh # The tail platform.py builds, made NSIS-relative ($APPDATA == %APPDATA%). tail = plat._startup_vbs() parts = tail.parts i = parts.index("Microsoft") rel = "\\".join(parts[i:]) # Microsoft\...\Startup\MeshBay Node.vbs assert rel in nsh, ( f"customUnInstall does not delete {rel!r} — the W3 autostart path " "changed and installer.nsh was not updated") def test_customInstall_stops_a_running_daemon_before_overwriting_it(): nsh = NSH.read_text(encoding="utf-8") body = _macro_body(nsh, "customInstall") assert "taskkill /IM meshbay-node.exe /F" in body # ── the autostart choice + the one-time elevated firewall step ────────────── def _macro_body(nsh: str, name: str) -> str: # \b after the name so "customInstall" does not also match the start of # "customInstallMode" (which is defined just above it in the file). return re.split(rf"!macro {re.escape(name)}\b", nsh, maxsplit=1)[1] \ .split("!macroend", 1)[0] def test_the_all_users_install_mode_page_is_suppressed(): """ MeshBay is per-user only — the keystore and the DPAPI-protected secrets are bound to the signed-in account (MESHBAY_DESIGN.md §11.2 / §7.5), and build.nsis forbids elevation — so electron-builder's "anyone who uses this computer / only me" page only ever showed its first option disabled. customInstallMode forcing $isForceCurrentInstall skips the page and pins per-user (multiUserUi.nsh: `${if} $isForceCurrentInstall == "1"` → abort). """ nsh = NSH.read_text(encoding="utf-8") mode = _macro_body(nsh, "customInstallMode") assert 'StrCpy $isForceCurrentInstall "1"' in mode def test_the_autostart_choice_is_a_radio_page_defaulting_to_service(): """ The old two nested Yes/No MessageBoxes are one nsDialogs page now, with the same three-way meaning: only-while-open / at-sign-in / background service. Background service is the default selection (MB_AutoMode "2"), set in customInit so a silent install — where the page never runs — still has a definite value. """ nsh = NSH.read_text(encoding="utf-8") page = _macro_body(nsh, "customPageAfterChangeDir") assert "Page custom mbAutostartPageCreate mbAutostartPageLeave" in page assert page.count("${NSD_CreateRadioButton}") == 3, ( "expected exactly three autostart options") assert "${NSD_Check} $MB_RbService" in page, ( "the background-service option must be the one checked by default") assert 'StrCpy $MB_AutoMode "2"' in _macro_body(nsh, "customInit"), ( "customInit must default MB_AutoMode to service mode for silent installs") # The MessageBox-driven flow is gone from customInstall entirely. assert "MessageBox MB_YESNO" not in _macro_body(nsh, "customInstall") def test_the_firewall_rules_are_set_up_in_every_autostart_mode(): """ A node that silently accepts no connections is the failure mode MESHBAY_DESIGN.md §7.5 calls out. So the rules go in whatever the autostart choice: folded into the service elevation for mode "2" (service-mode.ps1 does task + firewall in one UAC), their own single elevation for modes "0"/"1". Still ${Silent}-guarded — an unattended /S install cannot raise a UAC prompt, and falls back to Windows' own first-connection dialogs. """ nsh = NSH.read_text(encoding="utf-8") install = _macro_body(nsh, "customInstall") assert "${IfNot} ${Silent}" in install assert 'ExecShellWait "runas"' in install i_fw_check = install.index('firewall.ps1" check') i_svc_if = install.index('${If} $MB_AutoMode == "2"') i_svc_install = install.index('service-mode.ps1" -Action install') i_fw_add = install.index('firewall.ps1" add') # firewall check (unelevated) → service branch → firewall-only branch. assert i_fw_check < i_svc_if < i_svc_install < i_fw_add # The service branch's single elevation is service-mode.ps1; it does not # ALSO call firewall.ps1 add (service-mode.ps1 already covers that). assert 'firewall.ps1" add' not in install[i_svc_if:i_fw_add] def test_the_signin_mode_installs_the_per_user_startup_launcher(): """Mode "1" ("at sign-in") drops the Startup-folder .vbs via the frozen daemon's own `autostart install` verb — no admin, idempotent. The nearest enclosing choice must be `$MB_AutoMode == "1"`, so modes "0"/"2" skip it.""" nsh = NSH.read_text(encoding="utf-8") install = _macro_body(nsh, "customInstall") i_call = install.index('meshbay-node.exe" autostart install') last_if = install.rindex("${If} $MB_AutoMode ==", 0, i_call) assert install[last_if:i_call].startswith('${If} $MB_AutoMode == "1"'), ( "the Startup launcher must be gated on the at-sign-in choice") def test_reinstalling_with_everything_already_in_place_asks_nothing(): """ Get-NetFirewallRule needs no admin, only New/Remove do — so customInstall checks the firewall rules first, unelevated, and only elevates when something is actually missing. Without this, a repair or an upgrade that changes nothing would still re-trigger UAC. In service mode the task's presence is checked the same unelevated way (service.ps1 status), and both must be satisfied to skip. """ nsh = NSH.read_text(encoding="utf-8") install = _macro_body(nsh, "customInstall") check_line = 'firewall.ps1" check' assert check_line in install # The check runs before any elevation. assert install.index(check_line) < install.index('ExecShellWait "runas"') assert 'service.ps1" status' in install assert "Goto mb_auto_done" in install 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 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(): """ Register-ScheduledTask -LogonType S4U: no password stored anywhere, and — unlike LocalSystem/NetworkService — it loads this account's own profile, so %LOCALAPPDATA%\\meshbay\\ needs no relocation. Not `schtasks /create`: schtasks only *infers* the logon type from whether /rp is present, and both readings broke live on a blank-password account (common on a personal PC, 2026-09-05) -- `/rp ""` fails credential validation ("the user name or password is incorrect", even though nothing is wrong), and omitting /rp registers "Interactive only" instead of S4U, which never runs at boot and does not launch anything even run on demand while signed in. -LogonType S4U is explicit, so losing it (e.g. "simplifying" back to schtasks, or dropping -ErrorAction Stop so a permission failure silently falls through to "installed") would reintroduce one of those two live-reproduced failures. """ src = (WIN / "service.ps1").read_text(encoding="utf-8") # Isolate the actual "install" case from the docstring above it (which # names these same cmdlets in prose) -- checks below must see only code. lines = src.splitlines() install_start = next(i for i, line in enumerate(lines) if '"install" {' in line) remove_start = next(i for i, line in enumerate(lines) if '"remove" {' in line) install_block = "\n".join(lines[install_start:remove_start]) assert "New-ScheduledTaskTrigger -AtStartup" in install_block, ( "must trigger at boot, not at sign-in") assert "-LogonType S4U" in install_block, ( "must request S4U explicitly, not infer it from /rp") assert "Register-ScheduledTask" in install_block assert "-ErrorAction Stop" in install_block, ( "a permission failure must throw, not fall through as if it installed") assert "Get-Credential" not in src, "no password should ever be prompted for" assert "schtasks" not in install_block, ( "the install branch must not fall back to schtasks /create") # The install branch must not assign to `$action` (any case): that name is # this script's own [ValidateSet(...)][string]$Action parameter, and # `$action = New-ScheduledTaskAction ...` coerces the CimInstance to the # string "MSFT_TaskExecAction", which Register-ScheduledTask -Action then # refuses -- reproduced live 2026-09-05, the install path never created the # task at all until this was renamed. assert not re.search(r"(?im)^\s*\$action\s*=", install_block), ( "do not assign to $action in service.ps1 -- it shadows the [string]" "$Action parameter and Register-ScheduledTask -Action then gets a string") 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") HUB_STATIC = ROOT / "packages" / "meshbay-hub" / "src" / "meshbay_hub" / "static" def test_service_mode_toggle_elevates_the_same_script_the_installer_runs(): """ The installer's own mode question is effectively one-shot (it skips itself the moment the firewall rules exist for any reason, and per-user mode sets those up on its own with no Scheduled Task involved) -- so declining once, or the rules existing for any other reason, is a dead end through setup alone. The Node page's toggle is the other door in (and out), and it must drive service-mode.ps1 -- the exact script installer.nsh runs -- so the two paths can never disagree about what "service mode" means. One elevation (-Verb RunAs), no stored password. """ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8") assert "winElevateServiceMode" in main_js fn = main_js.split("function winElevateServiceMode", 1)[1] fn = fn[:fn.index("\n }\n")] assert "service-mode.ps1" in fn assert "-Verb RunAs" in fn or "'-Verb', 'RunAs'" in fn or "-Verb', 'RunAs'" in fn assert "Get-Credential" not in fn handler = main_js.split("ipcMain.handle('node:service-mode'", 1)[1] handler = handler[:handler.index("ipcMain.handle(")] assert "winElevateServiceMode" in handler assert "'install'" in handler or '"install"' in handler assert "'remove'" in handler or '"remove"' in handler def test_node_page_service_mode_toggle_is_wired_end_to_end(): """preload.js -> platform.js -> node-page.js, the same three-layer shape the existing autostart toggle uses. A break anywhere in this chain means the checkbox renders but does nothing, or never renders at all.""" preload = (CLIENT / "src" / "preload.js").read_text(encoding="utf-8") assert "serviceMode:" in preload assert "'node:service-mode'" in preload platform_js = (HUB_STATIC / "platform.js").read_text(encoding="utf-8") assert "serviceMode:" in platform_js assert "bridge.node.serviceMode('install')" in platform_js assert "bridge.node.serviceMode('remove')" in platform_js node_page = (HUB_STATIC / "node-page.js").read_text(encoding="utf-8") assert "platform.node.serviceMode.available" in node_page assert "platform.node.serviceMode.install()" in node_page assert "platform.node.serviceMode.remove()" in node_page # Checked state must reflect the CURRENT mode, not a separate flag -- # otherwise the toggle and the status panel above it could disagree. assert "info.mode === 'service'" in node_page def test_the_help_smoke_test_joins_multiline_output_before_matching(): """ `& exe --help 2>&1` is an ARRAY once the output wraps past one line, which it now does with `autostart`/`service` in the verb list. `$array -notmatch X` is a FILTER, not a boolean test -- it returns the *non-matching* elements, and any non-empty array is truthy in `if()` regardless of what is in it. Almost every help line lacks the literal string "meshbay-node", so an unjoined check throws unconditionally the moment --help exceeds one line: found when this specific verb list finally grew past that point, which is exactly the kind of one-off silent breakage a passing build yesterday gives no warning of today. """ src = (WIN / "build-node-runtime.ps1").read_text(encoding="utf-8") body = src.split("smoke test: meshbay-node --help", 1)[1] body = body[:800] assert '-join "`n"' in body, ( "the captured --help output must be joined to a single string before " "any -match/-notmatch check, or a multi-line result silently always " "fails the smoke test") # And the join has to happen at capture time, not on some other variable. assert '(& $exe --help 2>&1) -join' in body 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_node_start_provisions_before_it_ever_touches_the_service_task(): """ On a fresh install with service mode chosen, the Scheduled Task exists before anything is provisioned (node.toml is written by the wizard, not by the installer). node:start must call provisionNode() first and only then ask about the service task / spawn -- reversed, the very first "start" from the wizard would run (or query) an unconfigured daemon instead of the one it just told the caller to expect. A bare unprovisioned run is independently proven harmless (test_a_bare_invocation_with_no_config_yet_exits_cleanly in test_cli_dispatch.py), so this is about correctness of *this* call actually starting the daemon the wizard just configured, not about safety if the order were reversed. """ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8") body = main_js.split("ipcMain.handle('node:start'", 1)[1] body = body[:body.index("ipcMain.handle(")] provision_at = body.index("provisionNode(") service_check_at = body.index("winServiceTaskStatus") assert provision_at < service_check_at, ( "node:start checks the service task before provisioning — a fresh " "install's first Start would run/query the daemon before node.toml " "exists for it to read") def test_node_start_links_the_node_key_on_windows_not_only_linux(): """ The daemon comes up at 'waiting_for_account' until its Ed25519 key is linked to the hub account it runs as. The Linux branch of node:start does that link inline (`PUT /v1/users/me/node_key`); the win32 branch used to just return the first reachable status, so the Create Group wizard span on "Detecting local node…" for ever and the only way through was linking the key by hand on the Profile page. Pin that the win32 branch now performs the same link before it reports the node started. """ main_js = (CLIENT / "src" / "main.js").read_text(encoding="utf-8") body = main_js.split("ipcMain.handle('node:start'", 1)[1] body = body[:body.index("ipcMain.handle(")] win_branch = body.split("process.platform === 'win32'", 1)[1] win_branch = win_branch[:win_branch.index("process.platform !== 'linux'")] assert "linkNodeKeyAndAwaitRunning" in win_branch, ( "node:start's win32 branch never links the node key — the daemon will " "sit at waiting_for_account and the wizard will hang") helper = main_js.split("async function linkNodeKeyAndAwaitRunning", 1)[1] helper = helper[:2000] assert "/v1/users/me/node_key" in helper assert "waiting_for_account" in helper and "waiting_for_node_key" in helper def test_firewall_ps1_targets_both_executables_and_is_idempotent(): """One script, both rules — so installer.nsh only ever has to name it once on the way in and once on the way out.""" src = (ROOT / "packaging" / "win" / "firewall.ps1").read_text(encoding="utf-8") assert "MeshBay.exe" in src assert "node-runtime" in src and "meshbay-node.exe" in src # Remove-then-add: a re-run (reinstall, or install after a manual add) # must not leave duplicate rules. assert src.index("Remove-NetFirewallRule") < src.index("New-NetFirewallRule") def test_firewall_ps1_also_covers_lan_casting(): """ The WebRTC rules only reach MeshBay.exe / meshbay-node.exe; the cast HTTP relay (src/cast-relay.js, fixed TCP 19550-19553) and mDNS device discovery (src/cast-chromecast.js, bonjour-service, UDP 5353) are a separate surface on the client alone, and need their own ports and protocols. Ports here must agree with cast-relay.js's own constants and with the Linux definitions in packaging/firewall/*/meshbay-cast.xml — three descriptions of one port range that must not drift apart. """ src = (ROOT / "packaging" / "win" / "firewall.ps1").read_text(encoding="utf-8") assert "19550-19553" in src, "cast TCP range missing or does not match cast-relay.js" assert '"5353"' in src, "mDNS discovery port (UDP 5353) missing" relay = (CLIENT / "src" / "cast-relay.js").read_text(encoding="utf-8") assert "PORT_BASE = 19550" in relay and "PORT_COUNT = 4" in relay, ( "cast-relay.js's port range changed — update firewall.ps1 to match") firewalld = (ROOT / "packaging" / "firewall" / "firewalld" / "meshbay-cast.xml").read_text( encoding="utf-8") assert "19550-19553" in firewalld and "5353" in firewalld, ( "the Linux and Windows cast firewall definitions have drifted apart") def test_the_bundled_daemon_goes_on_the_user_path_and_comes_back_off(): """ The installer has no console entry point of its own; without this the operator has to `cd` into resources\\node-runtime\\ to run `meshbay-node`. The add uses stock WordFunc (no EnVar plugin — electron-builder's NSIS does not bundle it) and the same $INSTDIR-relative string on the way out. """ nsh = NSH.read_text(encoding="utf-8") assert "!insertmacro WordAdd" in nsh and "!insertmacro un.WordAdd" in nsh install = _macro_body(nsh, "customInstall") uninstall = _macro_body(nsh, "customUnInstall") assert 'HKCU "Environment" "Path"' in install assert "${WordAdd}" in install and '"+${MB_NODE_BIN}"' in install assert "${un.WordAdd}" in uninstall and '"-${MB_NODE_BIN}"' in uninstall # New shells need the broadcast to notice. assert "WM_WININICHANGE" in install and "WM_WININICHANGE" in uninstall # PATH points at the real .exe dir, so `where meshbay-node` resolves to the # binary the client and the W3 launcher use too — not a shim. assert 'MB_NODE_BIN "$INSTDIR\\resources\\node-runtime"' in nsh # ── ffmpeg: bundled by default (fetch-ffmpeg.ps1) ─────────────────────────── def test_fetch_ffmpeg_and_its_license_notice_exist(): assert (WIN / "fetch-ffmpeg.ps1").exists() notice = WIN / "LICENSE-ffmpeg.txt" assert notice.exists() text = notice.read_text(encoding="utf-8") assert "GPL" in text assert "ffmpeg.org" in text or "FFmpeg/FFmpeg" in text, ( "the notice must point at where the corresponding source actually is") def test_ffmpeg_is_pinned_to_a_dated_release_not_the_moving_latest_alias(): """ BtbN repoints the "latest" release on every auto-build (their asset filenames even embed a fresh git-describe each time), so a URL built from that alias silently changes what a build fetches. The dated tag (autobuild-YYYY-MM-DD-HH-MM) is immutable once published -- that is what makes the pinned checksum mean anything. """ src = (WIN / "fetch-ffmpeg.ps1").read_text(encoding="utf-8") tag_match = re.search(r'\$FFMPEG_TAG\s*=\s*"([^"]+)"', src) assert tag_match, "no $FFMPEG_TAG pin found" assert re.match(r"autobuild-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}$", tag_match.group(1)), ( f"{tag_match.group(1)!r} is not a dated release tag") assert "/releases/latest/" not in src and "/releases/download/latest/" not in src sha_match = re.search(r'\$FFMPEG_SHA256\s*=\s*"([0-9a-f]+)"', src) assert sha_match, "no $FFMPEG_SHA256 pin found" assert len(sha_match.group(1)) == 64, "not a full sha256 hex digest" assert '$FFMPEG_URL' in src and '$FFMPEG_TAG' in src.split("$FFMPEG_URL", 1)[1][:200], ( "the download URL must be built from the pinned tag") def test_ffplay_is_excluded_from_the_bundle(): """The vendor zip carries an SDL2 player MeshBay never invokes (~17 MB); bundling it would be the collect_all-everything instinct applied where a fixed allowlist is right instead.""" src = (WIN / "fetch-ffmpeg.ps1").read_text(encoding="utf-8") keep_block = src.split("$KEEP_FILES", 1)[1].split(")", 1)[0] assert "ffplay" not in keep_block assert "ffmpeg.exe" in keep_block and "ffprobe.exe" in keep_block def test_ffmpeg_bundling_is_the_default_not_opt_in(): """ Video streaming needs a real H.264 encoder (libx264, GPL -- no LGPL-only ffmpeg build has one), and asking an end user to separately run `winget install ffmpeg` is not viable for a non-technical install (needs network + winget present at that moment, fails silently). So bundling must be the default, with an explicit opt-out for local iteration -- the reverse of the old -FfmpegDir opt-in this replaced. """ runtime_src = (WIN / "build-node-runtime.ps1").read_text(encoding="utf-8") assert "SkipFfmpeg" in runtime_src assert "FfmpegDir" not in runtime_src, "the old opt-in mechanism should be gone, not parallel" assert "fetch-ffmpeg.ps1" in runtime_src win_src = (WIN / "build-win.ps1").read_text(encoding="utf-8") assert "SkipFfmpeg" in win_src assert "FfmpegDir" not in win_src # ------------------------------------------------------------------------ # The "Light" target: Electron client + UI, no bundled node. See # C:\Users\admin\devel\light-client.md for the evaluation. Weak, text- # reading evidence throughout, same reasoning as the rest of this file: # there is no electron-builder/PowerShell/NSIS runner here, and it is the # right kind of evidence for what these guard against -- a config drifting # back to carrying the node-runtime it must not, or the two orchestrators' # shared steps diverging silently. # ------------------------------------------------------------------------ def test_light_config_is_standalone_and_ships_no_node(): """ electron-builder.light.yml is passed via --config, which (per app-builder-lib/out/util/config/load.js's getConfig) makes electron- builder read ONLY that file -- package.json's own build field, and therefore its node-runtime/service*.ps1 extraResources, is never even loaded. Pins the config's own content regardless: it must name neither the node runtime nor the two service scripts, and must still carry firewall.ps1 (the one thing Light still needs -- packaging/win/ firewall.ps1's header explains why the client needs an inbound rule too, not only a node). """ assert LIGHT_YML.exists(), f"{LIGHT_YML} is missing" yml = LIGHT_YML.read_text(encoding="utf-8") assert "appId: org.meshbay.client.light" in yml assert "productName: MeshBay Light" in yml assert "output: dist-light" in yml assert "node-runtime" not in yml assert "service.ps1" not in yml assert "service-mode.ps1" not in yml assert "firewall.ps1" in yml assert "include: installer-light.nsh" in yml, ( "nsis.include must point at the Light NSIS customisation, not the " "default build/installer.nsh (Full's)") def test_light_config_keeps_the_same_no_admin_nsis_policy(): """Per-user, no elevation at install time -- identical policy to Full's package.json build.nsis, for the same reason (MESHBAY_DESIGN.md 11.2/7.5: the DPAPI-protected hub device key is account-bound).""" yml = LIGHT_YML.read_text(encoding="utf-8") assert "oneClick: false" in yml assert "perMachine: false" in yml assert "allowElevation: false" in yml def test_dist_win_light_delegates_to_the_light_orchestrator(): pkg = _pkg() scripts = pkg["scripts"] assert "dist:win:light" in scripts assert "build-win-light.ps1" in scripts["dist:win:light"] assert "dist:win" in scripts assert "build-win.ps1" in scripts["dist:win"] assert "build-win-light.ps1" not in scripts["dist:win"] def test_build_win_light_skips_the_node_runtime_step(): """The entire point of Light: no PyInstaller freeze, no ffmpeg fetch.""" assert BUILD_WIN_LIGHT.exists(), f"{BUILD_WIN_LIGHT} is missing" src = BUILD_WIN_LIGHT.read_text(encoding="utf-8") assert "build-node-runtime.ps1" not in src assert "electron-builder.light.yml" in src assert "--config" in src def test_build_orchestrators_share_the_common_steps_not_a_copy(): """ Node check / npm ci / Electron bump / sync-ui must live in exactly one place (build-win-common.ps1), dot-sourced by all three orchestrators -- a copy would let them drift the way the installer flow itself once did (the W3 one-shot dialog bug). Every orchestrator must call the shared functions, none may inline its own npm ci / Electron-bump logic. """ assert BUILD_WIN_COMMON.exists(), f"{BUILD_WIN_COMMON} is missing" common = BUILD_WIN_COMMON.read_text(encoding="utf-8") for fn in ("Assert-NodeVersion", "Invoke-NpmCi", "Invoke-ElectronBump", "Invoke-SyncUi"): assert f"function {fn}" in common, f"{fn} is not defined in build-win-common.ps1" full = (WIN / "build-win.ps1").read_text(encoding="utf-8") light = BUILD_WIN_LIGHT.read_text(encoding="utf-8") msix = BUILD_WIN_MSIX.read_text(encoding="utf-8") for src, name in ((full, "build-win.ps1"), (light, "build-win-light.ps1"), (msix, "build-win-msix.ps1")): assert '. (Join-Path $WinDir "build-win-common.ps1")' in src, ( f"{name} does not dot-source build-win-common.ps1") for fn in ("Assert-NodeVersion", "Invoke-NpmCi", "Invoke-ElectronBump", "Invoke-SyncUi"): assert fn in src, f"{name} does not call {fn}" assert "npm ci --ignore-scripts" not in src, ( f"{name} must not re-implement npm ci inline") def test_firewall_ps1_skips_the_node_rule_when_the_exe_is_missing(): """ The one behaviour Light structurally depends on: firewall.ps1 is shipped unforked (test_light_config_is_standalone_and_ships_no_node above), relying on `add` already skipping any rule whose target .exe does not exist -- true for "MeshBay Node" in a Light install, where node-runtime\\meshbay-node.exe is never there. If this guard were ever removed, New-NetFirewallRule would be pointed at a path that does not exist and Light's one firewall elevation would start failing. """ src = (WIN / "firewall.ps1").read_text(encoding="utf-8") add_block = src.split('if ($Action -eq "add")', 1)[1] assert "if (-not (Test-Path $r.Path))" in add_block skip_stanza = add_block.split("if (-not (Test-Path $r.Path))", 1)[1].split("}", 1)[0] assert "continue" in skip_stanza def test_light_installer_forces_per_user_and_elevates_firewall_once(): assert LIGHT_NSH.exists(), f"{LIGHT_NSH} is missing" nsh = LIGHT_NSH.read_text(encoding="utf-8") install = _macro_body(nsh, "customInstall") mode = _macro_body(nsh, "customInstallMode") assert 'StrCpy $isForceCurrentInstall "1"' in mode assert "${IfNot} ${Silent}" in install i_check = install.index('firewall.ps1" check') i_runas = install.index('ExecShellWait "runas"') assert i_check < i_runas, "the unelevated check must run before any elevation" assert 'firewall.ps1" add' in install assert "MB_AutoMode" not in nsh, "there is no autostart choice for Light" assert "Page custom" not in nsh assert "MessageBox MB_YESNO" not in install, ( "customInstall itself must ask nothing -- only customUnInstall's " "opt-in firewall-removal prompt uses MessageBox") def test_light_installer_never_touches_a_co_installed_full_clients_node(): """ Full and Light can be installed side by side (distinct appId/ productName/install dir -- test_light_config_is_standalone_and_ships_ no_node above). Light's installer/uninstaller must be a complete no-op with respect to anything a co-installed Full client owns: its node process, its Startup .vbs, its Scheduled Task, its own firewall rule. The easy mistake here is copy-pasting installer.nsh and trimming it, leaving one of these in by accident. """ nsh = LIGHT_NSH.read_text(encoding="utf-8") for forbidden in ("taskkill", 'HKCU "Environment"', "service.ps1", "service-mode.ps1", ".vbs", "MeshBay Node.vbs"): assert forbidden not in nsh, ( f"installer-light.nsh must not reference {forbidden!r} -- that " "belongs to a co-installed Full client, not to Light") def test_light_uninstaller_offers_to_remove_the_firewall_rules_default_no(): nsh = LIGHT_NSH.read_text(encoding="utf-8") uninstall = _macro_body(nsh, "customUnInstall") assert "${IfNot} ${Silent}" in uninstall assert "/SD IDNO" in uninstall assert 'firewall.ps1" remove' in uninstall assert 'ExecShellWait "runas"' in uninstall # ── the app-side gaps a bundle-less build would otherwise hit ────────────── def test_has_bundled_node_is_windows_only_and_packaged_only(): """ Off win32, or unpackaged (dev), this must stay true unconditionally -- only a packaged Windows build can even be Light, so nothing here may change today's behaviour for Linux, macOS or `npm start`. """ src = MAIN_JS.read_text(encoding="utf-8") assert "function hasBundledNode()" in src body = src.split("function hasBundledNode()", 1)[1].split("\n }", 1)[0] assert "process.platform === 'win32'" in body assert "app.isPackaged" in body assert "return true" in body, ( "must fall back to true (today's behaviour) off win32 / unpackaged") def test_node_bundled_ipc_channel_exists_end_to_end(): """main.js handles it, preload.js exposes it, platform.js wraps it -- the same three-layer shape every other node.* capability already has.""" main = MAIN_JS.read_text(encoding="utf-8") assert "ipcMain.handle('node:bundled'" in main assert "hasBundledNode()" in main preload = PRELOAD_JS.read_text(encoding="utf-8") assert "ipcRenderer.invoke('node:bundled')" in preload platform_js = (HUB_STATIC / "platform.js").read_text(encoding="utf-8") assert "bridge.node.bundled()" in platform_js def test_can_elevate_checks_service_mode_ps1_actually_exists(): """ app.isPackaged alone used to gate canElevate -- true for Light too, where service-mode.ps1 is never shipped, so the Node page would offer "background service" and only fail when clicked. Both nodeServiceStatus branches (service installed, and the per-user Startup branch) must go through the same helper rather than reimplementing the check. """ src = MAIN_JS.read_text(encoding="utf-8") assert "function winCanElevateServiceMode()" in src helper = src.split("function winCanElevateServiceMode()", 1)[1].split("\n }", 1)[0] assert "app.isPackaged" in helper assert "'service-mode.ps1'" in helper assert src.count("canElevate: winCanElevateServiceMode()") == 2, ( "both nodeServiceStatus branches must use the helper, not a bare " "app.isPackaged") assert "canElevate: app.isPackaged," not in src def test_startup_mode_is_null_not_a_lie_when_no_node_is_found(): """ The per-user Startup branch used to report mode: 'startup' unconditionally, so a Light install with no node anywhere (bundled or on PATH) showed a working-looking autostart dropdown for a node that did not exist -- node-page.js's showStartupRow is gated on typeof info.mode === 'string'. """ src = MAIN_JS.read_text(encoding="utf-8") assert "mode: bin ? 'startup' : null," in src assert "mode: 'startup'," not in src def test_create_group_page_falls_back_when_no_node_is_bundled(): """ The wizard's node-linking step is exactly the known "Detecting local node..." hang when nothing ever answers. Gating it on `bundled` (not just `available`, which is true for Light too -- both are Electron) routes a Light install to CreateGroupFormSimple: not a lesser feature, but the same node-free form a plain browser member already uses. """ src = (HUB_STATIC / "create-group-page.js").read_text(encoding="utf-8") body = src.split("export function CreateGroupPage(props) {", 1)[1] \ .split("\nfunction CreateGroupFormSimple", 1)[0] assert "platform.node.bundled()" in body assert "platform.node.available && bundled" in body assert "CreateGroupWizard" in body and "CreateGroupFormSimple" in body # ------------------------------------------------------------------------ # The "MSIX" target: same feature set as Full, packaged for Microsoft Store # submission instead of NSIS. See C:\Users\admin\devel\msix-installer.md for # the plan. Unlike Light, this target keeps the node runtime and both # service scripts -- what changes is packaging format, not what ships. # Weak, text-reading evidence throughout, same reasoning as the rest of # this file: there is no electron-builder/appx runner here either. # ------------------------------------------------------------------------ def test_msix_config_is_standalone_and_keeps_the_full_bundle(): """ Unlike Light, MSIX ships the same node-runtime/ffmpeg/service scripts as Full -- an AppX install never elevating (msix-installer.md 4) is not a reason to drop the daemon, only to change how its two elevated operations get triggered (see the two tests below). --config still means this file is read alone (app-builder-lib's getConfig), so it cannot silently inherit Full's package.json build.nsis or any signing config meant for NSIS. """ assert MSIX_YML.exists(), f"{MSIX_YML} is missing" yml = MSIX_YML.read_text(encoding="utf-8") assert "appId: org.meshbay.client" in yml assert "target: appx" in yml assert "output: dist-msix" in yml assert "node-runtime" in yml assert "service.ps1" in yml assert "service-mode.ps1" in yml assert "firewall.ps1" in yml def test_msix_identity_matches_the_partner_center_reservation(): """ identityName/publisher/publisherDisplayName are assigned by Partner Center's "App identity" page when the app name is reserved -- they cannot be chosen freely, and a mismatch fails Store validation outright rather than warning. Pins the exact reservation (done 2026-09-11) so a future edit cannot silently drift back to electron-builder's own unconfigured-build stand-in ("CN=ms", see windowsSignToolManager.js's computePublisherName) without a test noticing. publisherDisplayName is "MeshBay" as Partner Center assigned it, NOT package.json's author company name ("MeshBay Team") -- AppXOptions.d.ts's own default (company name from app metadata) would pick the wrong one if this were ever left unset instead of explicit. """ yml = MSIX_YML.read_text(encoding="utf-8") assert "identityName: MeshBay.MeshBay" in yml assert 'publisher: "CN=CE32BB0D-6B7C-4D3A-AA42-E259B778CAC9"' in yml assert "publisherDisplayName: MeshBay" in yml assert '"CN=ms"' not in yml, ( "must not have drifted back to electron-builder's own placeholder " "publisher") def test_msix_declares_no_csc_on_purpose(): """ No certificateFile/certificateSubjectName/certificateSha1 anywhere in this config -- per app-builder-lib's own windowsSignToolManager.js, an AppX target built with no certificate configured is logged as "Windows Store only build" and left unsigned; Microsoft signs it at publish time (msix-installer.md 3). Configuring a cert here would be wasted work, not extra safety, and would risk this target picking up whatever might one day be configured for Full's NSIS signing if it were ever added to this file instead of package.json's own build.win. """ yml = MSIX_YML.read_text(encoding="utf-8") for forbidden in ("certificateFile", "certificateSubjectName", "certificateSha1"): assert forbidden not in yml def test_msix_declares_the_network_capabilities_firewall_ps1_would_add(): """ Matches firewall.ps1's own rules, which are `-Profile Any` (private AND public network) -- msix-installer.md 8's #1 open item: whether Windows actually auto-exempts a full-trust packaged app on the strength of these declarations is unverified until sideloaded, but the declaration itself must at least match what the elevated NSIS path grants today, or an MSIX install would be silently narrower than Full/Light. """ yml = MSIX_YML.read_text(encoding="utf-8") caps_block = yml.split("capabilities:", 1)[1].split("customExtensionsPath", 1)[0] assert "internetClientServer" in caps_block assert "privateNetworkClientServer" in caps_block def test_msix_startup_task_targets_the_node_not_the_electron_shell(): """ addAutoLaunchExtension's built-in windows.startupTask (app-builder-lib's AppxTarget.js) always targets the package's own main executable -- the Electron shell -- which is not what "starts at sign in" means today (main.js's WIN_STARTUP_VBS launches meshbay-node.exe directly, keeping the daemon running whether or not the UI is ever opened). This config must NOT use addAutoLaunchExtension for that reason, and must instead supply its own extension via customExtensionsPath pointing at the node binary's in-package path -- app\\resources\\node-runtime\\meshbay-node.exe, derived from AppxTarget.js's own `"app\\\\" + appOutDir-relative path` mapping (build() in that file), which is not the same prefix process.resourcesPath resolves to at runtime and easy to get wrong. """ yml = MSIX_YML.read_text(encoding="utf-8") # The comment explaining *why* addAutoLaunchExtension is not used # necessarily names it -- check the directive, not the prose (the same # "parse directives, not text" mistake CLAUDE.md's engineering lessons # already record for a differently-shaped bug). lines = [ln.strip() for ln in yml.splitlines()] assert not any(ln.startswith("addAutoLaunchExtension:") for ln in lines), ( "must not set addAutoLaunchExtension -- it always targets the " "Electron shell, not the node binary (see this test's docstring)") assert "customExtensionsPath: build/appx-extensions.xml" in yml assert MSIX_EXTENSIONS_XML.exists(), f"{MSIX_EXTENSIONS_XML} is missing" ext = MSIX_EXTENSIONS_XML.read_text(encoding="utf-8") assert 'Category="windows.startupTask"' in ext assert 'Executable="app\\resources\\node-runtime\\meshbay-node.exe"' in ext assert 'EntryPoint="Windows.FullTrustApplication"' in ext def test_msix_ships_the_four_required_tile_images(): """ app-builder-lib's AppxTarget.js requires StoreLogo/Square44x44Logo/ Square150x150Logo/Wide310x150Logo regardless of showNameOnTiles, falling back to its own vendor-bundled samples if build/appx/ does not supply them. This repo points ELECTRON_BUILDER_WINDOWS_KITS_PATH at the system Windows SDK instead of that vendor bundle (build-win-msix.ps1), which has no samples to fall back to -- so a missing one here is a hard makeappx failure, not a cosmetic gap. See build/appx/README.md for where these came from. """ appx_assets = CLIENT / "build" / "appx" for name in ("StoreLogo.png", "Square44x44Logo.png", "Square150x150Logo.png", "Wide310x150Logo.png"): assert (appx_assets / name).exists(), f"{name} is missing from {appx_assets}" def test_build_win_msix_keeps_the_node_runtime_step(): """The opposite of Light's equivalent test: MSIX is Full's feature set, repackaged -- build-node-runtime.ps1 must still run.""" assert BUILD_WIN_MSIX.exists(), f"{BUILD_WIN_MSIX} is missing" src = BUILD_WIN_MSIX.read_text(encoding="utf-8") assert "build-node-runtime.ps1" in src assert "electron-builder.msix.yml" in src assert "--config" in src assert "--win appx" in src def test_dist_win_msix_delegates_to_the_msix_orchestrator(): pkg = _pkg() scripts = pkg["scripts"] assert "dist:win:msix" in scripts assert "build-win-msix.ps1" in scripts["dist:win:msix"] def test_build_win_msix_points_electron_builder_at_the_system_sdk(): """ electron-builder's own bundled AppX tooling download (winCodeSign-*.7z) extracts symlinks for binaries this target never uses and fails without SeCreateSymbolicLinkPrivilege -- reproduced on this machine's build shell. ELECTRON_BUILDER_WINDOWS_KITS_PATH (app-builder-lib's getWindowsKitsBundle) is the documented escape hatch; this must be set automatically, not left as a step a future build is expected to remember. """ src = BUILD_WIN_MSIX.read_text(encoding="utf-8") assert "ELECTRON_BUILDER_WINDOWS_KITS_PATH" in src assert "makeappx.exe" in src # ── main.js needs nothing new for this target ────────────────────────────── # # Unlike Light (which needed hasBundledNode/winCanElevateServiceMode/the # create-group gate because the bundle itself is smaller), MSIX ships # everything Full does, and the two elevation paths it cannot get from an # installer already exist independently of installer.nsh: # firewall.ps1's per-first-use Windows prompt (no admin needed for that # fallback -- see firewall.ps1's own header) and main.js's # winElevateServiceMode(), driven from the Node page ("the other door", # already exercised by test_can_elevate_checks_service_mode_ps1_actually_ # exists above) rather than from setup. There is deliberately no # MSIX-specific test here pinning main.js: the Light-target tests above # already pin that winCanElevateServiceMode() checks for service-mode.ps1's # presence generically, which is exactly what makes it work for a third # packaged target without being told about it.