Files
ucvl-home-vision/windows-power/README.md
T

139 lines
13 KiB
Markdown
Raw Permalink Normal View History

# Windows outbound safe power agent
This service implements the Windows side of `docs/superpowers/plans/2026-10-25-p15-power.md`. It uses an explicit protected choice between two fixed destinations, has no listening socket, no remote shell, no configurable URL/executable, and only accepts OP 2 (graceful local shutdown).
**P15 is the current development workstation. Keep `maintenance.lock` in place throughout development, deployment and review. Building, self-testing, installing and checking this agent do not require a real shutdown.**
## Build and verify without machine changes
Windows 10/11 with .NET Framework 4.8 and Windows PowerShell 5.1 or PowerShell 7 are supported. There are no NuGet downloads. `build.ps1` uses the installed Framework C# compiler, treats warnings as errors, and runs the embedded test suite by default.
```powershell
& .\windows-power\build.ps1
& .\windows-power\build\HomeVisionPower.exe --self-test
& .\windows-power\install.ps1 -Plan
& .\windows-power\uninstall.ps1 -Plan
```
All build outputs and test scratch directories live in ignored `windows-power/build/`. Self-tests use a fixed public test key, a local journal, an injected transport and an injected shutdown adapter. They do not make network requests, alter service registration/rights, or invoke Windows shutdown. Run them from the writable build directory.
The tests cover HMAC and response size, nonce/time/boot binding, exact expiry, malformed and non-shutdown commands, durable consumption before ACK, restart/duplicate replay, ACK failures, maintenance/stop/expiry races, journal corruption/capacity, DPAPI round trip and transport binding, fixed endpoint/redirect policy, safe check modes, and Windows API flags.
## Explicit transport selection
| Protected choice | Fixed endpoint | Channel protection |
| --- | --- | --- |
| `https` (default) | `https://home.ucvl.cn/api/device-power/agent` | TLS 1.2 with normal certificate validation plus signed HMAC messages |
| `tailscale` (explicit opt-in) | `http://100.115.230.91:8790/api/device-power/agent` | Active Tailscale WireGuard tunnel plus signed HMAC messages |
Tailscale must already be installed, connected and authorized to reach that server and port. Its tunnel provides the encryption for this explicit HTTP endpoint; there is no TLS on the HTTP hop itself. Tailscale's direct and relayed connections preserve end-to-end WireGuard encryption. [Tailscale encryption documentation](https://tailscale.com/docs/concepts/tailscale-encryption)
The agent does not install/configure Tailscale, change routes, or open a local port. Keep Tailscale active for the service to communicate. If the selected channel fails, the poll fails: there is **no alternate URL, redirect, HTTPS-to-HTTP downgrade or transport fallback**. HMAC verification, nonce/time/boot binding, replay protection, maintenance locks and ACK requirements are identical in both modes; the secret is never sent in an agent request.
New configurations store an explicit `transport` selector whose exact value is bound into the DPAPI encrypted secret. Editing or removing that selector does not switch a provisioned config; decryption fails. The service reads its choice once on startup and fixes its endpoint for that process. Older configurations without a selector remain HTTPS-only. A deliberate transport change requires stopping/locking the service, securely archiving its config, provisioning a new config with the matching secret and explicit choice, then reviewing `--check` before restarting. Do not edit the selector in place.
## Safety and protocol
- The service polls every 10 seconds without overlapping requests. Requests and responses are capped at 16 KiB. HTTPS mode requires TLS 1.2 and normal Windows certificate validation; explicit Tailscale mode relies on the active WireGuard tunnel. Both modes require HTTP 200 and reject redirects. The agent does not use proxy/default Windows credentials.
- The secret is base64 of exactly 32 random bytes. HMAC-SHA256 signs the ASCII **base64 payload**, not the decoded JSON. The lowercase 64-hex signature is compared in constant time. Responses bind the fresh request nonce, timestamp within 60 seconds, process boot ID and unexpired command ID. Unknown command fields, strings masquerading as OP values, arbitrary arguments and operations other than integer OP 2 are rejected.
- A new boot ID is created for every service process. Consumed 32-hex IDs are appended and flushed to a write-through journal **before** `scheduled` is sent. Only a signed HTTP 200 ACK response with the ACK nonce, valid time and `command:null` permits the final shutdown call. The server must only return that response after accepting the ACK. A lost, invalid or failed ACK permanently consumes the command; it is never retried for execution.
- Before and after the ACK, the service checks the lock, stop signal and expiry. Cancellation sends a best-effort `blocked` ACK; an API error sends `failed`. A server may already have recorded the first ACK, so actual RUN state must still come from fresh reachability probes. A scheduled ACK is not proof of physical power-off.
- `maintenance.lock` means `ready:false`, as do an exhausted journal and a stopping service. An inaccessible or missing safety directory fails closed. The service can read but cannot remove the maintenance lock or change its own executable/configuration.
- The journal holds at most 4,096 IDs, never silently evicts IDs, and stops accepting commands when full. Corruption also stops agent work. Retain it during upgrades. For manual repair or archival, first stop and lock the service, clear server pending commands and rotate the shared secret, then preserve the old journal as audit evidence before creating an empty one. Never delete it to retry a failed command.
- Windows receives `InitiateSystemShutdownEx(machine:null, timeout:0, forceAppsClosed:false, reboot:false)`. There is no forced application termination and no command-line shutdown fallback. An application with unsaved work may block shutdown; the agent does not escalate. [Microsoft API documentation](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdownexw) explains the asynchronous result and blocking behavior.
## Explicit installation after review
First provision the exact managed device ID and matching base64 random-32-byte secret on the server. Do not put the secret in device/catalog metadata, source control, a command-line argument or a transcript. The installer prompts securely; it sends the secret to the local executable through stdin, DPAPI-protects it with `LocalMachine` scope and application entropy, and clears the temporary unmanaged secret buffer.
In **elevated PowerShell**, from the repository, after reviewing a passing build:
```powershell
# The actual catalog ID, not the display name; installer securely prompts for the shared secret.
& .\windows-power\install.ps1 -DeviceId '<exact-server-device-id>'
# Explicit Tailnet mode when the reviewed internal route is intended:
& .\windows-power\install.ps1 -DeviceId '<exact-server-device-id>' -Transport tailscale
```
Choose one installation command. Omitting `-Transport` selects `https`; `-Transport` accepts only `https` or `tailscale`. Preview without installation using `install.ps1 -Plan -Transport tailscale`. The underlying local writer is `HomeVisionPower.exe --write-config DEVICE_ID CONFIG_PATH [https|tailscale]`, reading the base64 secret from stdin and refusing to overwrite a file. Use the installer so private parent ACLs exist before credential material is written.
Installation creates:
| Item | Setting |
| --- | --- |
| Service | `HomeVisionPower`, demand start, left stopped |
| Account | Dedicated virtual account `NT SERVICE\HomeVisionPower` |
| Required privilege | `SeShutdownPrivilege` only, configured with `sc.exe privs` |
| Account right | Only `SeShutdownPrivilege` is added to that service SID using LSA |
| Executable | `%ProgramFiles%\HomeVisionPower\HomeVisionPower.exe` |
| Configuration | `%ProgramData%\HomeVisionPower\config.json` |
| Transport | Explicit `https` or `tailscale`, bound to DPAPI and protected by the configuration ACL |
| Lock | `%ProgramData%\HomeVisionPower\maintenance.lock`, created by default |
| Journal and bounded log | `%ProgramData%\HomeVisionPower\state\` |
| ACLs | SYSTEM/Administrators full control; service read/execute on binary and config roots, modify only in `state` |
The installer does not start the service, unlock it, change RDP/Tailscale, open firewall ports or reboot. It refuses existing service/directories to avoid overwriting previous configuration/journals. A partial install is left disabled and locked for inspection. DPAPI `LocalMachine` depends on the ACL for protection from other local users; do not weaken those ACLs. Local administrators remain trusted.
The installer requests only `SeShutdownPrivilege`. Windows itself retains the baseline `SeChangeNotifyPrivilege` even when it is absent from a service's required-privilege list; this is normal SCM behavior, not an additional power/control grant. [Microsoft required-privileges documentation](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_required_privileges_infow)
Review the installed configuration and security, then explicitly start it **with the lock still present**:
```powershell
$agent = Join-Path $env:ProgramFiles 'HomeVisionPower\HomeVisionPower.exe'
& $agent --check
& "$env:WINDIR\System32\sc.exe" qc HomeVisionPower
& "$env:WINDIR\System32\sc.exe" qprivs HomeVisionPower
Get-Acl (Join-Path $env:ProgramData 'HomeVisionPower') | Format-List
Get-Acl (Join-Path $env:ProgramData 'HomeVisionPower\state') | Format-List
Start-Service HomeVisionPower
Get-Service HomeVisionPower
```
`--check` decrypts and validates the local configuration and reports the selected transport and maintenance lock; it makes no network request and cannot shut down. It does not verify the running service token, server configuration or live connectivity. No mode prints the secret, payload or signature.
For one safe end-to-end check of the selected channel and HMAC, **stop the service first** and leave the lock present. In Tailscale mode, confirm the existing Tailscale connection is active:
```powershell
Stop-Service HomeVisionPower
& $agent --check-online
Start-Service HomeVisionPower
```
`--check-online` sends exactly one signed heartbeat with `ready:false` and `ack:null`, validates the response, and rejects any returned command without consuming or executing it. It cannot shut down. Its fresh boot ID updates server agent state, so do not run it concurrently with the service. A successful result contains `network=signed-heartbeat-verified`. Its live heartbeat does not prove that native shutdown permissions or WOL are operational.
## Unlock only after work on P15 has ended
This is a separate, intentional operational step. Do not execute it during development. First stop the service, ensure no server command is pending, finish/save all workstation work, and only then remove the lock and start:
```powershell
Stop-Service HomeVisionPower
Remove-Item -LiteralPath (Join-Path $env:ProgramData 'HomeVisionPower\maintenance.lock')
Set-Service HomeVisionPower -StartupType Automatic
Start-Service HomeVisionPower
```
To return to maintenance, **stop first**, create the lock, then start. Stopping first waits for in-flight agent work to cancel; creating a lock cannot retract a shutdown already accepted by Windows.
```powershell
Stop-Service HomeVisionPower
[IO.File]::WriteAllText((Join-Path $env:ProgramData 'HomeVisionPower\maintenance.lock'), 'Maintenance: keep locked until work is finished.')
Start-Service HomeVisionPower
```
## Upgrade, recovery and uninstall
For an ordinary binary upgrade: stop the service, create/retain the lock, preserve `config.json` and `state/consumed.ids`, build and test the new binary in the source tree, copy only `build/HomeVisionPower.exe` over the installed executable as administrator, compare SHA256 hashes, run `--check`, and start with the lock present. Keep the installed ACLs intact. A service identity/configuration change requires separate review and reconfiguration, not automatic reinstall.
```powershell
& .\windows-power\uninstall.ps1 -Plan
# Explicit elevated removal, when wanted:
& .\windows-power\uninstall.ps1
```
Uninstall stops/disables the service, retains the lock, removes only the shutdown-right assignment for its service SID, and deletes the service registration. It preserves binary/configuration/journal/log files. It does not recursively delete directories. Before a clean reinstall, archive those files securely, revoke the server secret/pending commands, and intentionally remove the two reviewed installation directories; then install with a new secret. Never re-use an old journal-less secret to retry old commands.
## Verification limits
Source build, isolated protocol/engine/DPAPI/transport tests, installer plan output and script syntax can be checked without installation. **The native service logon, LSA right assignment, live network poll, real graceful shutdown and real WOL require separate operational verification.** No successful self-test claims those actions happened. This implementation must remain locked on the active P15 development host until the parent task's work is complete.