summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--docs/PACKAGING-GUIDE.md38
-rw-r--r--packages/meshbay-client/build/installer.nsh92
-rw-r--r--packages/meshbay-client/package.json10
-rw-r--r--packages/meshbay-client/src/main.js87
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/en.js1
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js1
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/static/node-page.js3
-rw-r--r--packages/meshbay-node/src/meshbay_node/daemon.py65
-rw-r--r--packages/meshbay-node/src/meshbay_node/platform.py103
-rw-r--r--packages/meshbay-node/tests/test_cli_dispatch.py1
-rw-r--r--packages/meshbay-node/tests/test_packaging_win.py141
-rw-r--r--packaging/win/README.md45
-rw-r--r--packaging/win/service-mode.ps155
-rw-r--r--packaging/win/service.ps187
14 files changed, 643 insertions, 86 deletions
diff --git a/docs/PACKAGING-GUIDE.md b/docs/PACKAGING-GUIDE.md
index c4f6b00..4dcda30 100644
--- a/docs/PACKAGING-GUIDE.md
+++ b/docs/PACKAGING-GUIDE.md
@@ -67,15 +67,24 @@ node (with `meshbay-common` inside it). There is no Windows hub.
### Install
Run the installer. It is **per-user** and lands in
-`%LOCALAPPDATA%\Programs\meshbay-client\` without needing admin rights. The
+`%LOCALAPPDATA%\Programs\MeshBay\` without needing admin rights. The
node daemon ships beside the app at `resources\node-runtime\meshbay-node.exe`;
the client finds it automatically.
-It does ask one thing: **"Allow MeshBay through Windows Firewall now?"** —
-say yes and one administrator confirmation adds both inbound rules the client
-and the node need for WebRTC. Say no and the install finishes the same either
-way; Windows will show its own "Allow access" dialog instead, once for each,
-the first time they actually need to accept a connection.
+It asks two things, both skippable:
+
+- **"Run MeshBay Node as a background service?"** — Yes starts the node **at
+ boot, before you even sign in**, and needs one administrator confirmation
+ (which also sets up the firewall rules, in the same step — see below). No
+ keeps the normal per-user mode: the node starts when you sign in, with no
+ admin needed, and you can turn autostart on later from the Node page.
+- **(per-user mode only) "Allow MeshBay through Windows Firewall now?"** — one
+ administrator confirmation adds the inbound rules the client and the node
+ need for WebRTC and casting. Declining is fine — Windows shows its own
+ "Allow access" dialog instead, the first time each is actually used.
+
+Running setup again (an upgrade, a repair install) asks neither question if
+the firewall rules are already there.
**ffmpeg** is required for video streaming and is *not* in the installer unless
it was built with `-FfmpegDir`. Otherwise install it separately
@@ -87,17 +96,26 @@ Open MeshBay and sign in. Use the **Node** page (or a terminal) to provision:
```
meshbay-node init
-meshbay-node autostart install # run the daemon at every sign-in (no admin)
+meshbay-node autostart install # per-user mode: run at every sign-in (no admin)
+meshbay-node service install # service mode: run at boot (needs an elevated prompt)
```
+The Node page's Start/Stop/Restart buttons work the same either way — they
+drive the Scheduled Task when service mode is active, or the daemon process
+directly otherwise.
+
Runtime data — `node.toml`, `keystore.enc`, `unlock.key`, `data\` — lives in
-`%LOCALAPPDATA%\meshbay\` and **survives uninstall/reinstall**.
+`%LOCALAPPDATA%\meshbay\` and **survives uninstall/reinstall**, in either mode
+(service mode runs as your own account too — never LocalSystem — so nothing
+about where your data lives changes).
### Uninstall
*Apps & features → MeshBay → Uninstall*, or the Start-menu *Uninstall MeshBay*
-entry. It stops a running daemon and removes the sign-in launcher; it does not
-touch `%LOCALAPPDATA%\meshbay\` (the keystore).
+entry. It stops a running daemon and removes the sign-in launcher; it offers
+(opt-in, one admin confirmation) to also remove the firewall rules and the
+boot-time service task, if you set one up. None of this touches
+`%LOCALAPPDATA%\meshbay\` (the keystore).
### Build from source
diff --git a/packages/meshbay-client/build/installer.nsh b/packages/meshbay-client/build/installer.nsh
index d2307c8..70858c6 100644
--- a/packages/meshbay-client/build/installer.nsh
+++ b/packages/meshbay-client/build/installer.nsh
@@ -1,16 +1,28 @@
; electron-builder NSIS customisation (auto-included: build/installer.nsh).
;
-; Per-user install, no elevation (package.json build.nsis). This does three
-; things beyond the default: put the bundled daemon on the user's PATH so
-; `meshbay-node` works in a terminal; offer to add the inbound firewall rules
-; in one elevated step instead of two "Allow access" dialogs later; and clean
-; up the one piece of state that lives outside the install directory (the W3
-; "run at sign-in" launcher).
+; Per-user install, no elevation (package.json build.nsis) -- that part never
+; changes. What this adds, all conditional on interactive setup (never
+; ${Silent}):
+; - the bundled daemon dir on the user's PATH, so `meshbay-node` works in a
+; terminal;
+; - a choice of autostart: the normal per-user Startup-folder launcher (no
+; admin, starts at sign-in -- see meshbay_node.platform._startup_vbs),
+; or a background-service mode (one admin confirmation, starts at boot,
+; no sign-in required -- see meshbay_node.platform.service_install and
+; packaging/win/service.ps1);
+; - the inbound firewall rules, folded into that SAME elevation when service
+; mode is chosen, or offered on their own otherwise -- never two UAC
+; prompts for one install;
+; - cleanup of whichever of those is outside $INSTDIR on the way out (the
+; Startup .vbs; the scheduled task and firewall rules, together, if the
+; user opts in).
;
; Deliberately NOT touched:
; - %LOCALAPPDATA%\meshbay\ (node.toml, keystore.enc, unlock.key, data/) --
; the keystore must survive an uninstall/reinstall; installers place files,
-; never remove secrets.
+; never remove secrets. This is also why service mode needs no code
+; changes to platform.py: it runs as this same user (S4U), so it is the
+; same profile either way.
!include "WinMessages.nsh"
!include "WordFunc.nsh"
@@ -40,27 +52,42 @@
WriteRegExpandStr HKCU "Environment" "Path" "$1"
SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000
- ; Firewall. MeshBay.exe / meshbay-node.exe (WebRTC) and MeshBay.exe again
- ; (LAN cast) each need an inbound allow, and Windows prompts "Allow access"
- ; the first time each does. A per-user installer cannot pre-create a
- ; firewall rule (that needs admin), so offer one elevated helper: one UAC
- ; prompt instead of up to four dialogs spread across first use.
- ;
- ; Checked first, UNELEVATED (Get-NetFirewallRule needs no admin, only
- ; New/Remove do) -- so re-running setup with the rules already in place
- ; asks nothing and never pops UAC again.
- nsExec::Exec '"${MB_PWSH}" -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\firewall.ps1" check'
- Pop $0
- ${If} $0 != 0
- ${IfNot} ${Silent}
+ ${IfNot} ${Silent}
+ ; Already configured -- an upgrade, or a repair install -- asks nothing.
+ ; Checked unelevated: reading firewall rules needs no admin, only
+ ; creating them does (same reasoning as the service task below). Whether
+ ; service mode or per-user mode was chosen last time, firewall rules
+ ; existing already means there is nothing left for this dialog to do.
+ nsExec::Exec '"${MB_PWSH}" -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\firewall.ps1" check'
+ Pop $0
+ ${If} $0 == 0
+ Goto mb_mode_done
+ ${EndIf}
+
+ ; The choice. Service mode needs admin to CREATE (a boot trigger touches
+ ; system-wide scheduler state -- the same reason /sc onlogon needed it
+ ; too); day-to-day start/stop from the Node page does not, once the task
+ ; exists, because Task Scheduler grants the owning user that much itself.
+ MessageBox MB_YESNO|MB_ICONQUESTION \
+ "Run MeshBay Node as a background service?$\n$\nIt starts automatically at boot, even before you sign in, and needs one administrator confirmation now (which also sets up the Windows Firewall rules, in the same step).$\n$\nChoose No for the normal per-user mode instead: it starts when you sign in, no admin needed, and you will be asked about the firewall rules separately." \
+ IDNO mb_peruser_mode
+
+ ; -- Service mode: one elevation, both jobs --------------------------
+ ExecShellWait "runas" "${MB_PWSH}" \
+ '-NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\service-mode.ps1" -Action install' \
+ SW_HIDE
+ Goto mb_mode_done
+
+ mb_peruser_mode:
+ ; -- Per-user mode: the firewall question stands on its own ----------
MessageBox MB_YESNO|MB_ICONQUESTION \
"Allow MeshBay through Windows Firewall now?$\n$\nMeshBay connects to other devices on your local network. Choosing Yes adds the rules in one step (Windows will ask for administrator confirmation). Choosing No is fine too -- Windows will ask you to allow access the first time MeshBay connects." \
- /SD IDYES IDNO mb_skip_fw
+ /SD IDYES IDNO mb_mode_done
ExecShellWait "runas" "${MB_PWSH}" \
'-NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\firewall.ps1" add' \
SW_HIDE
- mb_skip_fw:
- ${EndIf}
+
+ mb_mode_done:
${EndIf}
!macroend
@@ -73,18 +100,21 @@
WriteRegExpandStr HKCU "Environment" "Path" "$1"
SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000
- ; Offer to take the firewall rules back out (needs admin again). A stale
- ; allow-rule pointing at a deleted exe is inert, so this is opt-in and
- ; default-No -- a silent uninstall skips it entirely. customUnInstall runs
- ; before the files are removed, so firewall.ps1 is still there.
+ ; Offer to take the firewall rules, and the service task if one was set up,
+ ; back out together (needs admin again -- one prompt for both, same as
+ ; install). Both underlying removes are no-ops when there is nothing to
+ ; remove, so this is safe to run unconditionally regardless of which mode
+ ; was chosen. Stale rules/tasks are inert if left, so this is opt-in and
+ ; default-No; a silent uninstall skips it entirely. customUnInstall runs
+ ; before the files are removed, so service-mode.ps1 is still there.
${IfNot} ${Silent}
MessageBox MB_YESNO|MB_ICONQUESTION \
- "Remove MeshBay's Windows Firewall rules? This needs one administrator confirmation. They are harmless if left." \
- /SD IDNO IDNO mb_keep_fw
+ "Remove MeshBay's Windows Firewall rules and its boot-time service task, if you set one up? This needs one administrator confirmation. Both are harmless if left." \
+ /SD IDNO IDNO mb_keep_privileged
ExecShellWait "runas" "${MB_PWSH}" \
- '-NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\firewall.ps1" remove' \
+ '-NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\resources\service-mode.ps1" -Action remove' \
SW_HIDE
- mb_keep_fw:
+ mb_keep_privileged:
${EndIf}
; meshbay_node.platform._startup_vbs() -- if the user ran "meshbay-node
diff --git a/packages/meshbay-client/package.json b/packages/meshbay-client/package.json
index 7f5afcb..55b2dcf 100644
--- a/packages/meshbay-client/package.json
+++ b/packages/meshbay-client/package.json
@@ -1,6 +1,6 @@
{
"name": "meshbay-client",
- "version": "0.1.0",
+ "version": "1.0.0",
"description": "MeshBay desktop client — the interface ships with the application, not from the hub",
"license": "AGPL-3.0-or-later",
"author": "MeshBay Team <team@meshbay.org>",
@@ -37,6 +37,14 @@
{
"from": "../../packaging/win/firewall.ps1",
"to": "firewall.ps1"
+ },
+ {
+ "from": "../../packaging/win/service.ps1",
+ "to": "service.ps1"
+ },
+ {
+ "from": "../../packaging/win/service-mode.ps1",
+ "to": "service-mode.ps1"
}
]
},
diff --git a/packages/meshbay-client/src/main.js b/packages/meshbay-client/src/main.js
index b0505a9..15c3cc0 100644
--- a/packages/meshbay-client/src/main.js
+++ b/packages/meshbay-client/src/main.js
@@ -850,6 +850,38 @@ function registerBridge() {
});
}
+ // ── Windows: the opt-in Scheduled Task "service mode" ──────────────────────
+ // Set up once, elevated, at install time (build/installer.nsh + packaging/win
+ // /service.ps1 + /service-mode.ps1) or via `meshbay-node service install`
+ // from an elevated prompt — this process never creates or deletes it, only
+ // queries and drives an existing one, which needs no elevation (Task
+ // Scheduler grants the owning user that much itself). Kept in step with
+ // meshbay_node.platform.TASK_NAME / service_status().
+ const WIN_SERVICE_TASK = 'MeshBay Node';
+
+ function winServiceTaskStatus() {
+ return new Promise((resolve) => {
+ execFile('schtasks', ['/query', '/tn', WIN_SERVICE_TASK, '/fo', 'list'],
+ (err, stdout) => {
+ if (err) return resolve({ installed: false, state: '' });
+ const m = (stdout || '').split(/\r?\n/).find((l) => /^status:/i.test(l.trim()));
+ resolve({ installed: true, state: m ? m.split(':')[1].trim() : '' });
+ });
+ });
+ }
+
+ function winServiceTaskRun() {
+ return new Promise((resolve) => {
+ execFile('schtasks', ['/run', '/tn', WIN_SERVICE_TASK], () => resolve());
+ });
+ }
+
+ function winServiceTaskEnd() {
+ return new Promise((resolve) => {
+ execFile('schtasks', ['/end', '/tn', WIN_SERVICE_TASK], () => resolve());
+ });
+ }
+
async function spawnNodeDetached() {
const bin = await findNodeBinary();
if (!bin) throw new Error('meshbay-node not found on PATH');
@@ -875,8 +907,12 @@ function registerBridge() {
ipcMain.handle('node:installed', async () => {
if (process.platform === 'win32') {
- const bin = await findNodeBinary();
- return { installed: Boolean(bin), autostart: winAutostartInstalled() };
+ const [bin, svc] = await Promise.all([findNodeBinary(), winServiceTaskStatus()]);
+ return {
+ installed: Boolean(bin),
+ autostart: winAutostartInstalled(),
+ service: svc.installed,
+ };
}
if (process.platform !== 'linux') return { installed: false };
const unit = await new Promise((resolve) => {
@@ -897,16 +933,29 @@ function registerBridge() {
// looping — exactly the states this panel exists to show and act on.
ipcMain.handle('node:service-status', async () => {
if (process.platform === 'win32') {
- // No Task Scheduler to ask "is it running" — probe the daemon itself.
- // `installed` used to be winAutostartInstalled(), which is wrong: it
- // answers "does the Startup launcher exist", not "is there a daemon to
- // manage". The Node page's Stop/Restart buttons are gated on
- // `installed`, so with no autostart configured they silently vanished
- // — the daemon was perfectly manageable, just not launchable at
- // sign-in. `autostart` carries that state as its own field instead.
+ const svc = await winServiceTaskStatus();
+ if (svc.installed) {
+ // Service mode: Task Scheduler already tracks running/not, directly —
+ // no need to probe the daemon's own API for this panel.
+ const running = /running/i.test(svc.state);
+ return {
+ supported: true,
+ mode: 'service',
+ installed: true,
+ activeState: running ? 'active' : 'inactive',
+ subState: svc.state,
+ };
+ }
+ // Per-user Startup mode. `installed` used to be winAutostartInstalled(),
+ // which is wrong: it answers "does the Startup launcher exist", not "is
+ // there a daemon to manage". The Node page's Stop/Restart buttons are
+ // gated on `installed`, so with no autostart configured they silently
+ // vanished — the daemon was perfectly manageable, just not launchable
+ // at sign-in. `autostart` carries that state as its own field instead.
const [p, bin] = await Promise.all([probeNode(), findNodeBinary()]);
return {
supported: true,
+ mode: 'startup',
installed: Boolean(bin),
autostart: winAutostartInstalled(),
activeState: p ? 'active' : 'inactive',
@@ -939,7 +988,10 @@ function registerBridge() {
ipcMain.handle('node:service-stop', async () => {
if (process.platform === 'win32') {
- await killNodeProcesses(); // hard kill — no CTRL_CLOSE handler yet
+ const svc = await winServiceTaskStatus();
+ if (svc.installed) await winServiceTaskEnd();
+ await killNodeProcesses(); // hard kill — no CTRL_CLOSE handler yet;
+ // also the belt-and-suspenders in case /end left the process running
return { stopped: true };
}
if (process.platform !== 'linux') {
@@ -957,8 +1009,14 @@ function registerBridge() {
ipcMain.handle('node:service-restart', async () => {
if (process.platform === 'win32') {
+ const svc = await winServiceTaskStatus();
+ if (svc.installed) await winServiceTaskEnd();
await killNodeProcesses();
- await spawnNodeDetached();
+ if (svc.installed) {
+ await winServiceTaskRun();
+ } else {
+ await spawnNodeDetached();
+ }
const p = await waitForNode(Date.now() + 30000);
if (!p) throw new Error('node did not come back up within 30s');
return { restarted: true, ...p };
@@ -1064,7 +1122,12 @@ function registerBridge() {
if (process.platform === 'win32') {
if (opts && opts.hubUrl && opts.username) provisionNode(opts.hubUrl, opts.username);
await killNodeProcesses(); // clear a crash-looping one
- await spawnNodeDetached();
+ const svc = await winServiceTaskStatus();
+ if (svc.installed) {
+ await winServiceTaskRun();
+ } else {
+ await spawnNodeDetached();
+ }
const p = await waitForNode(Date.now() + 60000);
if (!p) throw new Error('the node did not start within 60s — run it from a '
+ 'terminal (`meshbay-node`) to see why');
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
index 09feaf5..196b9cc 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/en.js
@@ -736,6 +736,7 @@ export default {
'node.service_restarting': 'Restarting…',
'node.autostart_label': 'Start automatically at sign-in',
'node.autostart_updating': 'Updating…',
+ 'node.service_mode_hint': 'Running as a background service — it starts at boot, before sign-in.',
'node.offline': 'Node is offline',
'node.no_groups': 'No groups configured on this node.',
'node.retry': 'Retry',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
index 88e27f8..fe38500 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/locales/fr.js
@@ -679,6 +679,7 @@ export default {
'node.service_restarting': 'Redémarrage…',
'node.autostart_label': 'Démarrer automatiquement à l\'ouverture de session',
'node.autostart_updating': 'Mise à jour…',
+ 'node.service_mode_hint': 'Fonctionne comme service en arrière-plan — démarre au boot, avant l\'ouverture de session.',
'node.not_operator': 'Impossible de joindre votre node. Vérifiez qu\'il est en cours d\'exécution.',
'node.offline': 'Node hors ligne',
'node.retry': 'Réessayer',
diff --git a/packages/meshbay-hub/src/meshbay_hub/static/node-page.js b/packages/meshbay-hub/src/meshbay_hub/static/node-page.js
index c619f6e..d242b75 100644
--- a/packages/meshbay-hub/src/meshbay_hub/static/node-page.js
+++ b/packages/meshbay-hub/src/meshbay_hub/static/node-page.js
@@ -88,6 +88,9 @@ function NodeServicePanel({ onChanged }) {
${busy === 'restart' ? t('node.service_restarting') : t('node.service_restart')}</button>
`}
</div>
+ ${info.mode === 'service' && html`
+ <p class="node-hint">${t('node.service_mode_hint')}</p>
+ `}
${platform.node.autostart.available && typeof info.autostart === 'boolean' && html`
<label class="toggle-switch ${busy ? 'toggle-switch-disabled' : ''}">
<input type="checkbox" checked=${info.autostart} disabled=${!!busy}
diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py
index 37a2472..b932c16 100644
--- a/packages/meshbay-node/src/meshbay_node/daemon.py
+++ b/packages/meshbay-node/src/meshbay_node/daemon.py
@@ -1649,7 +1649,7 @@ def main() -> None:
choices=["init", "reset", "status", "gek-init",
"gek", "operator", "member", "group", "file",
"video", "denylist", "stun", "reload",
- "restart-daemon", "autostart",
+ "restart-daemon", "autostart", "service",
"calibrate-argon2"],
help="init: provision config + keystore | reset: erase all "
"node state | status: node state and keys "
@@ -1661,16 +1661,21 @@ def main() -> None:
"| stun list|add|remove|reset "
"| reload: re-read node.toml (hot; systemd or the "
"loopback API) | restart-daemon: restart the node "
- "(systemd unit, or the Windows autostart launcher) "
+ "(systemd unit, the Windows autostart launcher, or the "
+ "service task, whichever applies) "
"| autostart install|remove|start|stop|status "
- "(Windows: run meshbay-node at each sign-in) "
+ "(Windows: run meshbay-node at each sign-in, no admin) "
+ "| service install|remove|start|stop|status "
+ "(Windows: run at boot, before sign-in, needs admin "
+ "once to install) "
"| calibrate-argon2: benchmark")
parser.add_argument("subcommand", nargs="?",
help="'pair' for operator; list|invite|revoke|unpin for "
"member; list|add|remove for group; init|rotate for gek; "
"list|rm for file; rematch for video; show|clear for "
"denylist; list|add|remove|reset for stun; "
- "install|remove|start|stop|status for autostart")
+ "install|remove|start|stop|status for autostart and "
+ "for service")
parser.add_argument("target", nargs="?",
help="username for member invite|revoke|unpin; group name "
"for group add; file id for file rm; identifier for "
@@ -1845,8 +1850,9 @@ def main() -> None:
print("Could not unlink from hub (daemon not reachable).")
if sys.platform == "win32":
- from meshbay_node.platform import autostart_remove
+ from meshbay_node.platform import autostart_remove, service_remove
autostart_remove()
+ service_remove() # no-op, silently, if not elevated or not installed
else:
_sp.run(["systemctl", "--user", "disable", "--now", "meshbay-node"],
capture_output=True)
@@ -2107,7 +2113,14 @@ def main() -> None:
if args.command == "restart-daemon":
if sys.platform == "win32":
- from meshbay_node.platform import autostart_end, autostart_run
+ from meshbay_node.platform import (
+ autostart_end, autostart_run, service_end, service_run, service_status,
+ )
+ if service_status()["installed"]:
+ service_end()
+ service_run()
+ print("restarted the node (service task)")
+ return
autostart_end() # kill whatever is running now
try:
autostart_run()
@@ -2162,6 +2175,46 @@ def main() -> None:
sys.exit(1)
return
+ if args.command == "service":
+ from meshbay_node import platform as _plat
+ if sys.platform != "win32":
+ print("service mode is Windows-only — elsewhere use "
+ "'systemctl --user enable --now meshbay-node'.")
+ sys.exit(1)
+ sub = args.subcommand or "status"
+ if sub == "install":
+ try:
+ _plat.service_install()
+ except RuntimeError as e:
+ print(f"Could not install: {e}")
+ if "denied" in str(e).lower():
+ print("Run this from an elevated (Administrator) prompt.")
+ sys.exit(1)
+ print(f"Registered the {_plat.TASK_NAME!r} scheduled task — it starts "
+ "meshbay-node at boot, as this user, whether or not you have "
+ "signed in yet (no password stored).")
+ print("Start it now with: meshbay-node service start")
+ elif sub == "remove":
+ _plat.service_remove()
+ print(f"Removed the {_plat.TASK_NAME!r} scheduled task.")
+ elif sub == "start":
+ _plat.service_run()
+ print("started")
+ elif sub == "stop":
+ _plat.service_end()
+ print("stopped")
+ elif sub == "status":
+ st = _plat.service_status()
+ if st["installed"]:
+ print(f"service installed — {st['state'] or 'unknown state'}")
+ else:
+ print("service not installed — meshbay-node service install "
+ "(needs an elevated prompt)")
+ else:
+ print("service: install | remove | start | stop | status")
+ sys.exit(1)
+ return
+
if args.command == "denylist":
cfg = load_config(args.config or DEFAULT_CONFIG_PATH)
sub = args.subcommand or "show"
diff --git a/packages/meshbay-node/src/meshbay_node/platform.py b/packages/meshbay-node/src/meshbay_node/platform.py
index 3c160a1..9b18618 100644
--- a/packages/meshbay-node/src/meshbay_node/platform.py
+++ b/packages/meshbay-node/src/meshbay_node/platform.py
@@ -199,9 +199,8 @@ def ffprobe_cmd() -> str:
# to create — and this must work for an ordinary user with no admin rights.
# So: a `.vbs` launcher in the per-user Startup folder. wscript runs it hidden
# (Run(..., 0, ...)) at every sign-in; no console window, no admin, no
-# third-party dependency.
-
-TASK_NAME = "MeshBay Node" # the name the Electron client shows
+# third-party dependency. See the Service mode section below for the
+# boot-capable, admin-once alternative built on top of Task Scheduler instead.
def autostart_supported() -> bool:
@@ -277,3 +276,101 @@ def autostart_end() -> None:
if autostart_supported():
subprocess.run(["taskkill", "/IM", "meshbay-node.exe", "/F"],
capture_output=True)
+
+
+# ── Service mode (Windows, opt-in at install time) ───────────────────────────
+#
+# The Startup-folder .vbs above only ever runs after *this* user signs in. A
+# real Windows Service would run before anyone signs in, but under
+# LocalSystem/NetworkService — accounts with no normal user profile, so
+# %LOCALAPPDATA%\meshbay\ (config, keystore, data) would not exist for it.
+# Relocating storage to make that work is real surgery (Phase 2, deliberately
+# not this).
+#
+# The middle ground: a Scheduled Task, created once with admin rights, that
+# runs *as this user* at system 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 no special-casing at all. The cost: S4U carries no *network* credential
+# (no reaching a domain share as this user), which the node never needed
+# anyway — 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 did — see the autostart section above).
+# Querying, running and ending an *already-created* task, as the same user it
+# was registered for, does not — Task Scheduler grants the owner that much by
+# default, which is what lets the Node page drive it with no further prompts.
+
+TASK_NAME = "MeshBay Node" # the Scheduled Task's own name
+
+
+def service_supported() -> bool:
+ return sys.platform == "win32"
+
+
+def _current_user() -> str:
+ domain = os.environ.get("USERDOMAIN") or os.environ.get("COMPUTERNAME") or "."
+ user = os.environ.get("USERNAME") or ""
+ return f"{domain}\\{user}" if user else ""
+
+
+def _schtasks(*args: str) -> subprocess.CompletedProcess:
+ return subprocess.run(["schtasks", *args], capture_output=True, text=True)
+
+
+def service_status() -> dict:
+ """{'installed': bool, 'state': str}. 'state' is Task Scheduler's own word
+ ('Ready', 'Running', 'Disabled', ...), '' when not installed."""
+ if not service_supported():
+ return {"installed": False, "state": ""}
+ r = _schtasks("/query", "/tn", TASK_NAME, "/fo", "list")
+ if r.returncode != 0:
+ return {"installed": False, "state": ""}
+ state = ""
+ for line in r.stdout.splitlines():
+ if line.lower().startswith("status:"):
+ state = line.split(":", 1)[1].strip()
+ break
+ return {"installed": True, "state": state}
+
+
+def service_install(exe: str | None = None) -> None:
+ """
+ Register the boot-time Scheduled Task. Needs admin — raises RuntimeError
+ with schtasks' own message on failure, which is "Access is denied." when
+ not elevated.
+ """
+ if not service_supported():
+ raise RuntimeError("service mode is Windows-only")
+ exe = exe or _node_exe()
+ if not exe:
+ raise RuntimeError(
+ "cannot locate the meshbay-node launcher — pass its path, or run "
+ "this from where meshbay-node is on PATH")
+ user = _current_user()
+ if not user:
+ raise RuntimeError("could not determine the current user (USERNAME unset)")
+ r = _schtasks("/create", "/tn", TASK_NAME, "/tr", f'"{exe}"',
+ "/sc", "onstart", "/ru", user, "/rp", "", "/rl", "limited", "/f")
+ if r.returncode != 0:
+ raise RuntimeError(f"schtasks /create failed: {r.stderr.strip() or r.stdout.strip()}")
+
+
+def service_remove() -> None:
+ """Delete the Scheduled Task if present. Needs admin; silent otherwise
+ (mirrors autostart_remove — nothing to report if it was never installed)."""
+ if service_supported():
+ _schtasks("/delete", "/tn", TASK_NAME, "/f")
+
+
+def service_run() -> None:
+ """Start the task now. No admin needed for an already-registered task."""
+ if service_supported():
+ _schtasks("/run", "/tn", TASK_NAME)
+
+
+def service_end() -> None:
+ """Stop the running instance, if any. No admin needed."""
+ if service_supported():
+ _schtasks("/end", "/tn", TASK_NAME)
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():
diff --git a/packaging/win/README.md b/packaging/win/README.md
index 01c8d1a..7bbec13 100644
--- a/packaging/win/README.md
+++ b/packaging/win/README.md
@@ -7,11 +7,13 @@ Linux). `meshbay-common` rides along inside the node runtime.
## What the installer contains
```
-%LOCALAPPDATA%\Programs\meshbay-client\
+%LOCALAPPDATA%\Programs\MeshBay\ (productName, not the npm package name)
├─ MeshBay.exe Electron client
├─ resources\
│ ├─ app.asar src/ + ui/ (the interface ships in the package)
-│ ├─ firewall.ps1 adds/removes the two inbound rules (see below)
+│ ├─ firewall.ps1 adds/removes the four inbound rules (see below)
+│ ├─ service.ps1 install/remove/status/run/end the boot-time task
+│ ├─ service-mode.ps1 elevated helper: service.ps1 + firewall.ps1 in one UAC prompt
│ └─ node-runtime\
│ ├─ meshbay-node.exe frozen daemon (PyInstaller onedir)
│ ├─ _internal\ … its Python + deps (aiortc, av, aioquic, …)
@@ -22,6 +24,9 @@ Linux). `meshbay-common` rides along inside the node runtime.
Runtime data stays where the node already puts it: `%LOCALAPPDATA%\meshbay\`
(`node.toml`, `keystore.enc`, `unlock.key`, `data\`). The installer never writes
there and the uninstaller never deletes it — installers place files, not secrets.
+That is also why service mode needed no code changes to `platform.py`: it runs
+as this same signed-in user (S4U, see below), so it is the same profile either
+way — not LocalSystem/NetworkService, which would have none of this.
`build/installer.nsh` also adds `…\resources\node-runtime` to the **per-user**
`Path` (`HKCU\Environment`) so `meshbay-node` works in a terminal, and takes it
@@ -29,6 +34,42 @@ back out on uninstall. New shells only — a `WM_SETTINGCHANGE` broadcast nudges
open ones. It uses stock `WordFunc.nsh` (the `EnVar` plugin is not in
electron-builder's NSIS bundle).
+## Autostart: two modes, one choice at install time
+
+**Per-user (default, no admin).** A `.vbs` in the Startup folder
+(`meshbay_node.platform._startup_vbs`), toggled from the Node page or
+`meshbay-node autostart install|remove`. Starts when *this user* signs in.
+
+**Service mode (one admin confirmation, at install time only).** A Scheduled
+Task, `meshbay_node.platform.service_install` / `packaging/win/service.ps1`,
+that starts **at boot, before anyone signs in**. A real Windows Service would
+run under LocalSystem/NetworkService — accounts with no normal user profile,
+so `%LOCALAPPDATA%\meshbay\` (config, keystore, data) would not exist for it.
+Relocating storage to make that work is real surgery, deliberately not this.
+
+The alternative used instead: `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
+`%LOCALAPPDATA%\meshbay\` keeps working with zero code changes. The cost: S4U
+carries no network credential (cannot reach a domain share as this user),
+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 too, back when Task Scheduler
+was tried for the per-user mode and abandoned for exactly that reason).
+Querying, starting and stopping an *already-created* task 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
+(`src/main.js`'s `winServiceTaskStatus/Run/End`, mirroring `service.ps1`).
+
+**One elevation, not two.** Choosing service mode needs admin for both the
+Scheduled Task *and* the firewall rules; `service-mode.ps1` runs both from a
+single `ExecShellWait "runas"` in `installer.nsh`, so the choice costs exactly
+one UAC prompt. Re-running setup (an upgrade, a repair install) asks nothing
+if the firewall rules are already there — checked first, unelevated, the same
+pattern the per-user-only firewall step already used.
+
## Build
On a Windows machine with **Node ≥ 22**, **Python ≥ 3.12** (`py -3.12`) and
diff --git a/packaging/win/service-mode.ps1 b/packaging/win/service-mode.ps1
new file mode 100644
index 0000000..e522f04
--- /dev/null
+++ b/packaging/win/service-mode.ps1
@@ -0,0 +1,55 @@
+<#
+.SYNOPSIS
+ Elevated helper: set up (or tear down) service mode in ONE UAC prompt,
+ not two.
+
+.DESCRIPTION
+ "Run as a background service" is two things -- the boot-time Scheduled
+ Task and the firewall rules -- and needs one elevation, not one each.
+ build/installer.nsh runs this single script via ExecShellWait "runas"
+ for both the install-time choice and the uninstaller's cleanup, instead
+ of elevating service.ps1 and firewall.ps1 separately.
+
+ Each stays a script of its own rather than being folded together, so both
+ remain independently callable and testable -- the CLI does, through
+ meshbay-node service, and so does a later "just fix the firewall rules"
+ retry that has nothing to do with the service task.
+
+ Logs to the same file firewall.ps1 already uses, so both are visible in
+ one place: %TEMP%\meshbay-firewall.log.
+
+.PARAMETER Action
+ install service.ps1 install, then firewall.ps1 add
+ remove service.ps1 remove, then firewall.ps1 remove
+#>
+[CmdletBinding()]
+param(
+ [ValidateSet("install", "remove")]
+ [string]$Action = "install"
+)
+
+$here = $PSScriptRoot
+$log = Join-Path $env:TEMP "meshbay-firewall.log"
+$firewallAction = if ($Action -eq "install") { "add" } else { "remove" }
+$failed = $false
+
+"[{0}] service-mode {1}" -f (Get-Date -Format s), $Action | Add-Content $log
+
+try {
+ & (Join-Path $here "service.ps1") $Action
+}
+catch {
+ " service $Action failed: $_" | Add-Content $log
+ $failed = $true
+}
+
+try {
+ & (Join-Path $here "firewall.ps1") $firewallAction
+}
+catch {
+ " firewall $firewallAction failed: $_" | Add-Content $log
+ $failed = $true
+}
+
+if ($failed) { exit 1 }
+exit 0
diff --git a/packaging/win/service.ps1 b/packaging/win/service.ps1
new file mode 100644
index 0000000..936c060
--- /dev/null
+++ b/packaging/win/service.ps1
@@ -0,0 +1,87 @@
+<#
+.SYNOPSIS
+ Install/remove/query/run/end the "MeshBay Node" boot-time Scheduled Task.
+
+.DESCRIPTION
+ A real Windows Service runs under LocalSystem/NetworkService before anyone
+ signs in -- but those accounts have no normal user profile, and this app's
+ entire design keeps node.toml, the keystore and all data under the signed-in
+ user's own %LOCALAPPDATA%\meshbay\. Running as LocalSystem would not find
+ any of it.
+
+ The middle ground, and what this script sets up: a Scheduled Task that runs
+ AS THIS USER at system 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 %LOCALAPPDATA%\meshbay\
+ keeps working with zero changes. The cost: S4U carries no network
+ credential (no reaching a domain share as this user), which the node never
+ needed -- everything it touches is local disk plus outbound internet.
+
+ Mirrors meshbay_node.platform.service_install/_remove/_status/_run/_end --
+ same TASK_NAME, same flags -- so the CLI and the installer agree on what
+ "installed" means. install/remove need admin (a boot trigger touches
+ system-wide scheduler state); status/run/end do not, once the task exists,
+ because Task Scheduler grants the owning user that much by default -- which
+ is what lets the Node page's Start/Stop/Restart drive it with no further
+ UAC prompts.
+
+ Shipped as an extraResource at <install>\resources\service.ps1, so it
+ locates meshbay-node.exe from its own path.
+
+.PARAMETER Action
+ install | remove | status | run | end
+#>
+[CmdletBinding()]
+param(
+ [ValidateSet("install", "remove", "status", "run", "end")]
+ [string]$Action = "status"
+)
+
+# Not "Stop": schtasks writes its normal "task not found" outcome to stderr,
+# and with ErrorActionPreference=Stop that promotes to a terminating error
+# even through a 2>$null redirect (a native command's stderr is converted to
+# an ErrorRecord before the redirect discards it). Every exit path below
+# checks $LASTEXITCODE explicitly instead.
+$TASK_NAME = "MeshBay Node"
+$resources = $PSScriptRoot
+$node = Join-Path $resources "node-runtime\meshbay-node.exe"
+
+function Get-CurrentUser {
+ $domain = $env:USERDOMAIN
+ if (-not $domain) { $domain = $env:COMPUTERNAME }
+ return "$domain\$env:USERNAME"
+}
+
+switch ($Action) {
+ "install" {
+ if (-not (Test-Path $node)) { throw "meshbay-node.exe not found at $node" }
+ $user = Get-CurrentUser
+ & schtasks /create /tn $TASK_NAME /tr "`"$node`"" /sc onstart /ru $user /rp "" /rl limited /f
+ if ($LASTEXITCODE -ne 0) { throw "schtasks /create failed (exit $LASTEXITCODE)" }
+ Write-Host "service: installed ($user, runs at boot)"
+ }
+ "remove" {
+ & schtasks /delete /tn $TASK_NAME /f 2>$null | Out-Null
+ Write-Host "service: removed"
+ }
+ "status" {
+ $out = & schtasks /query /tn $TASK_NAME /fo list 2>$null
+ if ($LASTEXITCODE -ne 0) {
+ Write-Output "NOT_INSTALLED"
+ exit 1
+ }
+ $line = $out | Select-String "^Status:"
+ $state = if ($line) { ($line -replace "^Status:\s*", "").Trim() } else { "unknown" }
+ Write-Output "INSTALLED:$state"
+ exit 0
+ }
+ "run" {
+ & schtasks /run /tn $TASK_NAME
+ if ($LASTEXITCODE -ne 0) { throw "schtasks /run failed (exit $LASTEXITCODE)" }
+ }
+ "end" {
+ & schtasks /end /tn $TASK_NAME
+ if ($LASTEXITCODE -ne 0) { throw "schtasks /end failed (exit $LASTEXITCODE)" }
+ }
+}