Skip to content

feat(service): run Windows control daemon via per-user Scheduled Task - #378

Merged
kombuchapunk merged 3 commits into
mainfrom
fix/bug-184-windows-service
Dec 4, 2026
Merged

kombuchapunk merged 3 commits into
mainfrom
fix/bug-184-windows-service

Conversation

@kombuchapunk

Copy link
Copy Markdown
Collaborator

Summary

Rebases #317 (preserving @connorburgess's original commit and DCO attribution) onto main (adding LOCAL_COPY_VIA_SCHTASKS = 4 to proto/sessionpipe/v1/local.proto and regenerating schemas) and hardens the Windows per-user Scheduled Task service manager (\sessionpipe\<label>) after multi-model adversarial QA.

Closes #184
Supersedes #317

Hardening & Security Fixes

  • PowerShell 5.1 & launcher injection defense: escapes ASCII ' plus Unicode curly single quotes (U+2018..U+201B) in psQuote, rejects ASCII control chars (0x00..0x1F) and JS line separators (U+2028/U+2029) in unsafeWord, neutralizes line terminators in launcherText() comments, and escapes U+2028/U+2029 in the embedded JSON config line for lossless round-tripping.
  • Win32 argv & ReDoS safety: replaces trailing-backslash regex in word() with a linear-time loop and properly doubles trailing backslashes before closing quotes in taskArguments.
  • Launcher resilience: adds exponential crash backoff (5s..60s, reset after 60s healthy uptime; immediate first exit-75 update restart), 5 MiB log rotation to .1 (0600) with immediate parent fd close, case-insensitive Windows env key deduplication (Path/PATH, AppData/APPDATA), and clean SIGTERM/SIGINT teardown.
  • Rollback, teardown & serviceEnv fixes:
    • Restores both previous launcher .cjs and previous task XML when schtasks /Run fails after /Create /F, and restarts the previous task on identical-launcher failure.
    • Preserves launcher .cjs and surfaces errors when schtasks /Delete fails for reasons other than task-not-found (piping stderr in execQuiet).
    • Stops launcher PID trees before schtasks /End, resolves conhost.exe via system32(), and makes taskXmlBytes() CRLF-idempotent.
    • Makes WORLD env filter case-insensitive in serviceEnv() so mixed-case AppData/LocalAppData/UserProfile are preserved on Windows.
    • Prioritizes explicit InstallOptions.user, preserves USERNAME without USERDOMAIN, and reports installed: true when a task exists with a missing launcher so repair works automatically.

Verification

  • Verified across multi-model adversarial QA (Gemini 4 Neon, Codex, and Claude Opus 5.5) — Pass-2 audits passed with 0 blocker/high/medium issues.
  • npm run lint, npm run typecheck, npm run build, npm run schemas -- --check, npm run conformance, and 100% test coverage passing.

connorburgess and others added 3 commits December 3, 2026 16:21
… logon

Symptom: on Windows `control pair`, `connect`, `pool on` and `ask on` ended
with "no service manager for this platform yet; run `sessionpipe control run`
yourself", so the daemon lived as long as the terminal it was started in (#184).

Core's service module gains a third manager beside launchd and systemd: a
per-user scheduled task, \sessionpipe\<label>, registered from a definition
with a logon trigger that names the user, which needs no administrator.

- No window: a task that runs node.exe directly opens a terminal window at
  every logon (measured on Windows 11), so the task runs it under
  `conhost.exe --headless`.
- Task Scheduler gives an action no environment, keeps none of its output and
  restarts it on no exit code. The task runs a small launcher script
  (%LOCALAPPDATA%\sessionpipe\service\<label>.cjs) that starts the service
  with the environment it was given, appends its output to the log, starts it
  again at once on 75 and after 5 s on a failure, and ends with it on 0. What
  it runs is one line of JSON, so nothing is read by cmd.exe; only the node
  and the launcher path are on the task's command line, and one with a quote
  or a % is refused with why.
- The launcher sets SESSIONPIPE_SERVICE=schtasks:<its pid>, and restartVia
  answers "schtasks" only for the process whose parent that is, as it does for
  the supervisor. The daemon exits 75 and the launcher starts the new copy.
- `schtasks /End` ends conhost alone, so replacing or removing the task also
  stops the launcher and what it runs, found by command line and never by a
  pid written down earlier.
- Task Scheduler and the process list are read through one PowerShell script
  (cmdlets only), which prints a number and writes text to a file as UTF-8.
- pair, update and doctor name the task and Task Scheduler; status no longer
  says updates on Windows run only while `control run` is running; update
  writes down who is mid-turn before it replaces the task, which ends its
  processes outright.
- A service of a sessionpipe's own (SESSIONPIPE_SERVICE_LABEL) is given
  APPDATA and LOCALAPPDATA too: on Windows its files are under those, and
  without them it came up on the account's real ones.

Tests that used win32 as the platform with no manager use freebsd.

Signed-off-by: connorburgess <connorburgesscodes@gmail.com>
…ing, and teardown

- Escape Windows PowerShell 5.1 curly single quotes (U+2018..U+201B) in psQuote
  alongside ASCII single quotes to prevent single-quote breakout injection.
- Reject ASCII control characters (0x00..0x1F) in unsafeWord and double trailing
  backslashes before closing quotes in taskArguments for Win32 argv safety.
- Use path.win32.dirname in taskXml <WorkingDirectory> so Windows paths resolve
  consistently across platforms.
- Harden the Windows launcher script:
  - Exponential crash backoff (5s..60s) on rapid failures and repeated rapid
    exit 75s (first update exit 75 still restarts immediately; backoff resets
    after 60s healthy uptime).
  - Log rotation at 5 MiB to .1 with 0600 permissions, immediate parent log fd
    close after spawn (preventing fd leaks and Windows log file locks), and
    spawn try/catch safety.
  - Case-insensitive Windows env key deduplication (e.g. Path vs PATH, AppData
    vs APPDATA) so Task Scheduler's default Path does not shadow service.env.
  - Clean SIGTERM/SIGINT teardown clearing restart timers and stopping the child.
- Use case-insensitive USERDOMAIN/USERNAME lookup in installService, skip
  removing task XML on dryRun, clean stale XML on uninstallService, and forward
  caller env as shell in CLI service helpers (with mixed-case Path support).

Refs #184

Signed-off-by: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com>
…indows scheduled task

- Neutralize line terminators (including U+2028/U+2029) in launcherText() label
  comments, escape U+2028/U+2029 in the embedded JSON line for clean round-trip
  parsing, and reject U+2028/U+2029 in unsafeWord().
- Make WORLD regex case-insensitive in serviceEnv() so Windows mixed-case
  AppData/LocalAppData/UserProfile are preserved for isolated services.
- Harden Windows installService() rollback:
  - Keep launcher and XML writes inside the rollback guard and only remove
    the XML file in finally if written.
  - When /Run fails after /Create /F replaced the task, re-register the
    previous task XML alongside restoring the previous launcher .cjs.
  - When re-installing an identical launcher after stopping a running task,
    attempt schtasks /Run on failure to restore service availability.
- Preserve launcher .cjs and surface errors when schtasks /Delete fails for
  reasons other than task-not-found (and pipe stderr in execQuiet so missing
  task errors are inspectable).
- Replace /\+$/ in word() with a linear-time trailing-backslash loop (eliminates
  CodeQL polynomial ReDoS).
- Prioritize explicit InstallOptions.user over env and preserve USERNAME when
  USERDOMAIN is absent.
- Report installed=true in Windows serviceState() when a task is registered
  even if its launcher .cjs is missing, enabling automatic repair.
- Resolve conhost.exe via system32(), make taskXmlBytes() CRLF-idempotent, and
  stop launcher PIDs before schtasks /End (skipping conhost taskkill unless
  /End failed with no known launcher PID) to minimize PID-reuse windows.

Refs #184

Signed-off-by: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com>
@kombuchapunk
kombuchapunk merged commit 0091011 into main Dec 4, 2026
18 checks passed
@kombuchapunk
kombuchapunk deleted the fix/bug-184-windows-service branch December 4, 2026 00:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Windows: nothing keeps the control daemon running (a per-user scheduled task beside launchd and systemd?)

2 participants