aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/src
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-node/src')
-rw-r--r--packages/meshbay-node/src/meshbay_node/daemon.py65
-rw-r--r--packages/meshbay-node/src/meshbay_node/platform.py103
2 files changed, 159 insertions, 9 deletions
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)