feat: add typed data and views with scoped device power

This commit is contained in:
Codex
2026-10-25 14:35:24 +08:00
parent 5b99a7e9fc
commit ca60398dea
65 changed files with 4238 additions and 231 deletions
+2
View File
@@ -0,0 +1,2 @@
build/
*.user
+138
View File
@@ -0,0 +1,138 @@
# 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.
+27
View File
@@ -0,0 +1,27 @@
// Loaded only by explicit elevated install/uninstall scripts. Never by the agent.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public static class HomeVisionServiceRights {
[StructLayout(LayoutKind.Sequential)] struct LsaObjectAttributes { public uint Length; public IntPtr Root, ObjectName; public uint Attributes; public IntPtr Descriptor, Quality; }
[StructLayout(LayoutKind.Sequential)] struct LsaString { public ushort Length, MaximumLength; public IntPtr Buffer; }
[DllImport("advapi32.dll")] static extern uint LsaOpenPolicy(IntPtr system, ref LsaObjectAttributes attributes, uint access, out IntPtr policy);
[DllImport("advapi32.dll")] static extern uint LsaAddAccountRights(IntPtr policy, byte[] sid, LsaString[] rights, uint count);
[DllImport("advapi32.dll")] static extern uint LsaRemoveAccountRights(IntPtr policy, byte[] sid, [MarshalAs(UnmanagedType.Bool)] bool all, LsaString[] rights, uint count);
[DllImport("advapi32.dll")] static extern uint LsaClose(IntPtr policy);
[DllImport("advapi32.dll")] static extern int LsaNtStatusToWinError(uint status);
static void Check(uint result) { if (result != 0) throw new Win32Exception(LsaNtStatusToWinError(result)); }
public static void SetShutdownRight(SecurityIdentifier identity, bool grant) {
var attributes = new LsaObjectAttributes { Length = (uint)Marshal.SizeOf(typeof(LsaObjectAttributes)) };
IntPtr policy;
Check(LsaOpenPolicy(IntPtr.Zero, ref attributes, 0x00000810, out policy)); // lookup names + create account
IntPtr text = Marshal.StringToHGlobalUni("SeShutdownPrivilege");
try {
byte[] sid = new byte[identity.BinaryLength]; identity.GetBinaryForm(sid, 0);
var rights = new[] { new LsaString { Buffer = text, Length = 38, MaximumLength = 40 } };
Check(grant ? LsaAddAccountRights(policy, sid, rights, 1) : LsaRemoveAccountRights(policy, sid, false, rights, 1));
} finally { Marshal.FreeHGlobal(text); LsaClose(policy); }
}
}
+16
View File
@@ -0,0 +1,16 @@
[CmdletBinding()]
param([switch]$SkipTests)
$ErrorActionPreference = 'Stop'
$compiler = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
if (!(Test-Path -LiteralPath $compiler)) { throw 'The .NET Framework 4 C# compiler is required.' }
$outputDir = Join-Path $PSScriptRoot 'build'
New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
$sources = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'src') -Filter '*.cs' | ForEach-Object FullName)
$sources += Join-Path $PSScriptRoot 'tests\SelfTests.cs'
& $compiler /nologo /warnaserror+ /optimize+ /target:exe /platform:anycpu "/out:$outputDir\HomeVisionPower.exe" /reference:System.ServiceProcess.dll /reference:System.Web.Extensions.dll /reference:System.Security.dll $sources
if ($LASTEXITCODE -ne 0) { throw 'Compilation failed.' }
if (!$SkipTests) {
& (Join-Path $outputDir 'HomeVisionPower.exe') --self-test
if ($LASTEXITCODE -ne 0) { throw 'Self-tests failed.' }
}
Write-Output "Built $outputDir\HomeVisionPower.exe"
+92
View File
@@ -0,0 +1,92 @@
[CmdletBinding()]
param(
[ValidatePattern('^[A-Za-z0-9_-]{1,128}$')][string]$DeviceId,
[Security.SecureString]$SecretBase64,
[ValidateSet('https', 'tailscale')][string]$Transport = 'https',
[switch]$Plan
)
$ErrorActionPreference = 'Stop'
$Transport = $Transport.ToLowerInvariant()
$serviceName = 'HomeVisionPower'
$serviceAccount = "NT SERVICE\$serviceName"
$binRoot = Join-Path $env:ProgramFiles $serviceName
$dataRoot = Join-Path $env:ProgramData $serviceName
$stateRoot = Join-Path $dataRoot 'state'
$binary = Join-Path $binRoot 'HomeVisionPower.exe'
$sourceBinary = Join-Path $PSScriptRoot 'build\HomeVisionPower.exe'
$scExe = Join-Path $env:WINDIR 'System32\sc.exe'
if ($Plan) {
[pscustomobject]@{
service = $serviceName; account = $serviceAccount; start = 'demand'; autoStartOrShutdown = $false
privilege = 'SeShutdownPrivilege'; bin = $binRoot; data = $dataRoot
transport = $Transport
secretProtection = 'DPAPI LocalMachine + SYSTEM/Administrators/service read ACL'
maintenanceLock = 'created before service registration; retained after installation'
} | ConvertTo-Json
return
}
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run the explicit installer in an elevated PowerShell.' }
if (!$DeviceId) { throw '-DeviceId is required and must match the server managed asset ID.' }
if (!(Test-Path -LiteralPath $sourceBinary -PathType Leaf)) { throw 'Run build.ps1 and review its passing self-tests first.' }
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) { throw 'Service already exists. Stop it and review the update steps in README.md.' }
if ((Test-Path -LiteralPath $binRoot) -or (Test-Path -LiteralPath $dataRoot)) { throw 'Installation directories already exist. Preserve the config/journal and use the documented upgrade or recovery steps.' }
if (!$SecretBase64) { $SecretBase64 = Read-Host 'Enter the matching server secret (base64 random 32 bytes)' -AsSecureString }
function Set-PrivateDirectoryAcl([string]$Path, [Security.Principal.SecurityIdentifier]$Identity, [Security.AccessControl.FileSystemRights]$ServiceRights) {
$acl = New-Object Security.AccessControl.DirectorySecurity
$acl.SetAccessRuleProtection($true, $false)
$inherit = [Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
$propagation = [Security.AccessControl.PropagationFlags]::None
$allow = [Security.AccessControl.AccessControlType]::Allow
foreach ($id in @('S-1-5-18', 'S-1-5-32-544')) {
$sid = New-Object Security.Principal.SecurityIdentifier($id)
$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', $inherit, $propagation, $allow)))
}
if ($Identity) { $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($Identity, $ServiceRights, $inherit, $propagation, $allow))) }
Set-Acl -LiteralPath $Path -AclObject $acl
}
function Invoke-ServiceControl([string[]]$Arguments) {
& $scExe @Arguments
if ($LASTEXITCODE -ne 0) { throw "Service Control Manager operation failed: $($Arguments[0])" }
}
# Secure directories BEFORE copying executable or writing any credential material.
foreach ($path in @($binRoot, $dataRoot, $stateRoot)) {
New-Item -ItemType Directory -Path $path | Out-Null
Set-PrivateDirectoryAcl -Path $path -ServiceRights ReadAndExecute
}
[IO.File]::WriteAllText((Join-Path $dataRoot 'maintenance.lock'), 'Installation safety lock. Remove explicitly only after all work on this host is finished.')
Copy-Item -LiteralPath $sourceBinary -Destination $binary
Invoke-ServiceControl @('create', $serviceName, 'binPath=', ('"' + $binary + '" --service'), 'start=', 'demand', 'obj=', $serviceAccount, 'DisplayName=', 'Home Vision Safe Power Agent')
try {
Invoke-ServiceControl @('sidtype', $serviceName, 'unrestricted')
Invoke-ServiceControl @('privs', $serviceName, 'SeShutdownPrivilege')
Invoke-ServiceControl @('description', $serviceName, 'Outbound fixed-endpoint polling; signed shutdown-only commands; maintenance lock defaults on.')
$serviceSid = ([Security.Principal.NTAccount]$serviceAccount).Translate([Security.Principal.SecurityIdentifier])
Add-Type -Path (Join-Path $PSScriptRoot 'ServiceRights.cs')
[HomeVisionServiceRights]::SetShutdownRight($serviceSid, $true)
Set-PrivateDirectoryAcl -Path $binRoot -Identity $serviceSid -ServiceRights ReadAndExecute
Set-PrivateDirectoryAcl -Path $dataRoot -Identity $serviceSid -ServiceRights ReadAndExecute
Set-PrivateDirectoryAcl -Path $stateRoot -Identity $serviceSid -ServiceRights Modify
# Secret goes to stdin, never a process argument, command echo or plaintext file.
$secretPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecretBase64)
try {
[Runtime.InteropServices.Marshal]::PtrToStringBSTR($secretPointer) | & $binary --write-config $DeviceId (Join-Path $dataRoot 'config.json') $Transport
if ($LASTEXITCODE -ne 0) { throw 'Protected configuration creation failed.' }
} finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($secretPointer) }
& $binary --check
if ($LASTEXITCODE -ne 0) { throw 'Installed configuration check failed.' }
$sourceHash = (Get-FileHash -LiteralPath $sourceBinary -Algorithm SHA256).Hash
$installedHash = (Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash
if ($sourceHash -ne $installedHash) { throw 'Installed binary hash mismatch.' }
Write-Output "Installed SHA256 $installedHash"
Write-Output "Installed and STOPPED with maintenance.lock present. Review first, then explicitly Start-Service $serviceName."
} catch {
# Do not auto-start or remove evidence/config on partial installation.
Invoke-ServiceControl @('config', $serviceName, 'start=', 'disabled')
throw
}
+175
View File
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace HomeVisionPower {
internal sealed class ProtocolException : Exception { public ProtocolException(string message) : base(message) {} }
internal sealed class ShutdownCommand { public string Id; public long Expires; }
internal interface IClock { long UnixSeconds { get; } }
internal interface IShutdown { void ShutdownGracefully(); }
internal interface ITransport { string Post(string body); }
internal interface IJournal { bool Ready { get; } bool TryConsume(string id); }
internal sealed class MaintenanceSafety {
readonly string path;
public MaintenanceSafety(string path) { this.path = Path.GetFullPath(path); }
public bool Ready {
get {
if (!Directory.Exists(Path.GetDirectoryName(path))) return false;
try { File.GetAttributes(path); return false; }
catch (FileNotFoundException) { return true; }
catch (Exception) { return false; }
}
}
}
// A single append-only, write-through file is also the agent's process lock.
// Never evict IDs automatically: a full/corrupt journal makes the service fail closed.
internal sealed class FileJournal : IJournal, IDisposable {
public const int Capacity = 4096;
readonly HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal);
FileStream stream;
bool failed;
public FileJournal(string path) {
try {
stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.WriteThrough);
if (stream.Length > Capacity * 33 || stream.Length % 33 != 0) throw new IOException("Invalid journal length");
using (var reader = new StreamReader(stream, Encoding.ASCII, false, 4096, true)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (!Protocol.IsId(line) || !seen.Add(line)) throw new IOException("Invalid journal record");
}
}
stream.Position = stream.Length;
} catch { Dispose(); throw; }
}
public bool Ready { get { return stream != null && !failed && seen.Count < Capacity; } }
public bool TryConsume(string id) {
if (!Protocol.IsId(id)) throw new IOException("Invalid command ID");
if (!Ready || seen.Contains(id)) return false;
try {
byte[] line = Encoding.ASCII.GetBytes(id + "\n");
stream.Write(line, 0, line.Length);
stream.Flush(true);
seen.Add(id);
return true;
} catch { failed = true; throw; }
}
public void Dispose() { if (stream != null) { stream.Dispose(); stream = null; } }
}
internal static class Protocol {
public const int MaxBytes = 16384;
static readonly UTF8Encoding StrictUtf8 = new UTF8Encoding(false, true);
public static JavaScriptSerializer Json() { return new JavaScriptSerializer { MaxJsonLength = MaxBytes, RecursionLimit = 8 }; }
public static bool IsId(string value) { return value != null && Regex.IsMatch(value, "\\A[0-9a-f]{32}\\z"); }
public static Dictionary<string, object> Map(params object[] pairs) {
var m = new Dictionary<string, object>();
for (int i = 0; i < pairs.Length; i += 2) m[(string)pairs[i]] = pairs[i + 1];
return m;
}
public static void ExactKeys(Dictionary<string, object> value, params string[] keys) {
if (value == null || value.Count != keys.Length) throw new ProtocolException("Unexpected message fields");
foreach (string key in keys) if (!value.ContainsKey(key)) throw new ProtocolException("Missing message field");
}
static string Text(Dictionary<string, object> m, string key) {
var value = m[key] as string;
if (value == null) throw new ProtocolException("Invalid text field");
return value;
}
static long Integer(Dictionary<string, object> m, string key) {
object value = m[key];
if (!(value is int) && !(value is long)) throw new ProtocolException("Invalid integer field");
return Convert.ToInt64(value);
}
public static bool ConstantTimeEquals(byte[] a, byte[] b) {
if (a == null || b == null || a.Length != b.Length) return false;
int difference = 0;
for (int i = 0; i < a.Length; i++) difference |= a[i] ^ b[i];
return difference == 0;
}
static byte[] Mac(string payload, byte[] key) {
if (key == null || key.Length != 32) throw new ProtocolException("Secret must be 32 bytes");
using (var hmac = new HMACSHA256(key)) return hmac.ComputeHash(Encoding.ASCII.GetBytes(payload));
}
public static string Sign(object body, byte[] key) {
string payload = Convert.ToBase64String(StrictUtf8.GetBytes(Json().Serialize(body)));
string signature = BitConverter.ToString(Mac(payload, key)).Replace("-", "").ToLowerInvariant();
string envelope = Json().Serialize(Map("payload", payload, "signature", signature));
if (Encoding.UTF8.GetByteCount(envelope) > MaxBytes) throw new ProtocolException("Message too large");
return envelope;
}
public static ShutdownCommand VerifyResponse(string body, byte[] key, string nonce, string boot, long now) {
try {
if (body == null || StrictUtf8.GetByteCount(body) > MaxBytes || !IsId(nonce) || !IsId(boot)) throw new ProtocolException("Invalid envelope");
var envelope = Json().Deserialize<Dictionary<string, object>>(body);
ExactKeys(envelope, "payload", "signature");
string payload = Text(envelope, "payload"), signature = Text(envelope, "signature");
if (!Regex.IsMatch(signature, "\\A[0-9a-f]{64}\\z")) throw new ProtocolException("Invalid signature");
byte[] receivedMac = new byte[32];
for (int i = 0; i < 32; i++) receivedMac[i] = Convert.ToByte(signature.Substring(i * 2, 2), 16);
if (!ConstantTimeEquals(Mac(payload, key), receivedMac)) throw new ProtocolException("Signature mismatch");
byte[] decoded = Convert.FromBase64String(payload);
if (Convert.ToBase64String(decoded) != payload) throw new ProtocolException("Noncanonical payload");
var response = Json().Deserialize<Dictionary<string, object>>(StrictUtf8.GetString(decoded));
ExactKeys(response, "nonce", "at", "command");
if (Text(response, "nonce") != nonce) throw new ProtocolException("Nonce mismatch");
long at = Integer(response, "at");
if (at < now - 60 || at > now + 60) throw new ProtocolException("Response timestamp outside window");
if (response["command"] == null) return null;
var command = response["command"] as Dictionary<string, object>;
ExactKeys(command, "id", "op", "bootId", "expires");
string id = Text(command, "id");
long expires = Integer(command, "expires");
if (!IsId(id) || Integer(command, "op") != 2 || Text(command, "bootId") != boot || expires <= now) throw new ProtocolException("Invalid shutdown command");
return new ShutdownCommand { Id = id, Expires = expires };
} catch (ProtocolException) { throw; }
catch (Exception) { throw new ProtocolException("Malformed signed response"); }
}
}
internal sealed class AgentEngine {
readonly string device, boot;
readonly byte[] key;
readonly IJournal journal;
readonly MaintenanceSafety safety;
readonly IClock time;
readonly ITransport transport;
readonly IShutdown shutdown;
readonly Func<bool> stopping;
public AgentEngine(string device, byte[] key, string boot, IJournal journal, MaintenanceSafety safety, IClock time, ITransport transport, IShutdown shutdown, Func<bool> stopping) {
this.device = device; this.key = key; this.boot = boot; this.journal = journal; this.safety = safety;
this.time = time; this.transport = transport; this.shutdown = shutdown; this.stopping = stopping;
}
bool Ready { get { return !stopping() && safety.Ready && journal.Ready; } }
ShutdownCommand Exchange(object ack) {
string nonce = Guid.NewGuid().ToString("N");
string body = Protocol.Sign(Protocol.Map("deviceId", device, "bootId", boot, "nonce", nonce, "at", time.UnixSeconds, "ready", Ready, "ack", ack), key);
string response = transport.Post(body);
return Protocol.VerifyResponse(response, key, nonce, boot, time.UnixSeconds);
}
void Ack(ShutdownCommand command, string status, string result) {
if (Exchange(Protocol.Map("id", command.Id, "status", status, "result", result)) != null) throw new ProtocolException("ACK must not contain a command");
}
void BestEffortAck(ShutdownCommand command, string status, string result) { try { Ack(command, status, result); } catch (Exception) {} }
public string Poll() {
if (stopping()) return "stopping";
ShutdownCommand command = Exchange(null);
if (command == null) return "idle";
try {
if (!journal.TryConsume(command.Id)) { BestEffortAck(command, "blocked", "already_consumed_or_journal_full"); return "consumed_or_journal_full"; }
} catch (Exception) { BestEffortAck(command, "failed", "journal_write_failed"); return "journal_write_failed"; }
if (!Ready || command.Expires <= time.UnixSeconds) { BestEffortAck(command, "blocked", "maintenance_stopped_or_expired"); return "blocked"; }
// This ACK is attempted once. Timeout or invalid response permanently cancels execution.
try { Ack(command, "scheduled", "graceful_shutdown_scheduled"); }
catch (Exception) { return "ack_failed_command_consumed"; }
if (!Ready || command.Expires <= time.UnixSeconds) { BestEffortAck(command, "blocked", "cancelled_after_ack"); return "cancelled_after_ack"; }
try { shutdown.ShutdownGracefully(); return "shutdown_requested"; }
catch (Exception) { BestEffortAck(command, "failed", "windows_shutdown_failed"); return "windows_shutdown_failed"; }
}
}
}
+152
View File
@@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace HomeVisionPower {
internal sealed class SystemClock : IClock {
public long UnixSeconds { get { return (DateTime.UtcNow.Ticks - 621355968000000000L) / TimeSpan.TicksPerSecond; } }
}
internal sealed class FixedTransport : ITransport {
// Resolve the explicit protected choice once. Never accept a URL or downgrade/fallback.
readonly string endpoint;
public FixedTransport(string mode) { endpoint = EndpointFor(mode); }
public static string EndpointFor(string mode) {
if (mode == "https") return "https://home.ucvl.cn/api/device-power/agent";
if (mode == "tailscale") return "http://100.115.230.91:8790/api/device-power/agent";
throw new ProtocolException("Transport must be https or tailscale");
}
public HttpWebRequest CreateRequest(int bytes) {
if (bytes < 0 || bytes > Protocol.MaxBytes) throw new ProtocolException("Request too large");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.ContentLength = bytes;
request.AllowAutoRedirect = false;
request.Timeout = 8000;
request.ReadWriteTimeout = 8000;
request.KeepAlive = false;
request.Proxy = null;
request.UseDefaultCredentials = false;
return request;
}
public string Post(string body) {
byte[] bytes = Encoding.UTF8.GetBytes(body);
var request = CreateRequest(bytes.Length);
using (Stream output = request.GetRequestStream()) output.Write(bytes, 0, bytes.Length);
using (var response = (HttpWebResponse)request.GetResponse()) {
if (response.StatusCode != HttpStatusCode.OK || response.ContentLength > Protocol.MaxBytes) throw new ProtocolException("HTTP response rejected");
using (Stream input = response.GetResponseStream())
using (var data = new MemoryStream()) {
var block = new byte[2048];
int read;
while ((read = input.Read(block, 0, block.Length)) > 0) {
if (data.Length + read > Protocol.MaxBytes) throw new ProtocolException("Response too large");
data.Write(block, 0, read);
}
return new UTF8Encoding(false, true).GetString(data.ToArray());
}
}
}
}
internal interface IWindowsShutdownApi { void EnablePrivilege(); void DisablePrivilege(); void Initiate(uint timeout, bool force, bool reboot); }
internal sealed class WindowsShutdown : IShutdown {
readonly IWindowsShutdownApi api;
public WindowsShutdown(IWindowsShutdownApi api) { this.api = api; }
public void ShutdownGracefully() {
api.EnablePrivilege();
try { api.Initiate(0, false, false); }
finally { api.DisablePrivilege(); }
}
}
internal sealed class WindowsShutdownApi : IWindowsShutdownApi {
[StructLayout(LayoutKind.Sequential)] struct Luid { public uint Low; public int High; }
[StructLayout(LayoutKind.Sequential)] struct TokenPrivileges { public uint Count; public Luid Luid; public uint Attributes; }
[DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool LookupPrivilegeValue(string system, string name, out Luid luid);
[DllImport("advapi32.dll", SetLastError = true)] static extern bool AdjustTokenPrivileges(IntPtr token, bool disableAll, ref TokenPrivileges state, uint length, IntPtr previous, IntPtr returnedLength);
[DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool InitiateSystemShutdownEx(string machine, string message, uint timeout, [MarshalAs(UnmanagedType.Bool)] bool forceAppsClosed, [MarshalAs(UnmanagedType.Bool)] bool reboot, uint reason);
static void SetPrivilege(bool enabled) {
IntPtr token;
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, 0x0028, out token)) throw new Win32Exception(Marshal.GetLastWin32Error());
try {
Luid luid;
if (!LookupPrivilegeValue(null, "SeShutdownPrivilege", out luid)) throw new Win32Exception(Marshal.GetLastWin32Error());
var privileges = new TokenPrivileges { Count = 1, Luid = luid, Attributes = enabled ? 2U : 0U };
bool success = AdjustTokenPrivileges(token, false, ref privileges, 0, IntPtr.Zero, IntPtr.Zero);
int error = Marshal.GetLastWin32Error();
if (!success || error != 0) throw new Win32Exception(error);
} finally { CloseHandle(token); }
}
public void EnablePrivilege() { SetPrivilege(true); }
public void DisablePrivilege() { SetPrivilege(false); }
public void Initiate(uint timeout, bool force, bool reboot) {
// Local machine only; planned application maintenance. Never shell out.
if (!InitiateSystemShutdownEx(null, "Home Vision: requested graceful shutdown", timeout, force, reboot, 0x80040001U)) throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
internal sealed class AgentConfig {
public string DeviceId;
public byte[] Secret;
public string Transport = "https";
static readonly byte[] Entropy = Encoding.UTF8.GetBytes("HomeVisionPower/config/v1");
public static void Validate(string device, byte[] secret) {
if (device == null || !Regex.IsMatch(device, "\\A[A-Za-z0-9_-]{1,128}\\z")) throw new ProtocolException("Invalid device ID");
if (secret == null || secret.Length != 32) throw new ProtocolException("Secret must be 32 bytes");
}
public static void WriteProtected(string path, string device, byte[] secret) {
WriteProtected(path, device, secret, "https");
}
public static void WriteProtected(string path, string device, byte[] secret, string transport) {
Validate(device, secret);
FixedTransport.EndpointFor(transport);
// Bind the choice into DPAPI: editing/removing transport cannot switch an existing config.
byte[] encrypted = ProtectedData.Protect(secret, TransportEntropy(transport), DataProtectionScope.LocalMachine);
string content = Protocol.Json().Serialize(Protocol.Map("deviceId", device, "transport", transport, "protectedSecret", Convert.ToBase64String(encrypted)));
// Installer must set parent ACLs before invoking this path; refuse accidental replacement.
using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) {
byte[] bytes = Encoding.UTF8.GetBytes(content); file.Write(bytes, 0, bytes.Length); file.Flush(true);
}
}
static byte[] TransportEntropy(string transport) { return Encoding.UTF8.GetBytes("HomeVisionPower/config/v2/" + transport); }
public static AgentConfig Load(string path) {
var file = new FileInfo(path);
if (!file.Exists || file.Length > Protocol.MaxBytes) throw new IOException("Configuration missing or oversized");
var map = Protocol.Json().Deserialize<Dictionary<string, object>>(File.ReadAllText(path, Encoding.UTF8));
bool legacy = map != null && !map.ContainsKey("transport");
if (legacy) Protocol.ExactKeys(map, "deviceId", "protectedSecret");
else Protocol.ExactKeys(map, "deviceId", "transport", "protectedSecret");
var result = new AgentConfig { DeviceId = map["deviceId"] as string, Transport = legacy ? "https" : map["transport"] as string };
FixedTransport.EndpointFor(result.Transport);
result.Secret = ProtectedData.Unprotect(Convert.FromBase64String((string)map["protectedSecret"]), legacy ? Entropy : TransportEntropy(result.Transport), DataProtectionScope.LocalMachine);
Validate(result.DeviceId, result.Secret);
return result;
}
}
internal static class AgentCheck {
public static string Run(AgentConfig config, string safetyPath, bool online, ITransport transport, IClock clock) {
AgentConfig.Validate(config.DeviceId, config.Secret);
FixedTransport.EndpointFor(config.Transport);
bool unlocked = new MaintenanceSafety(safetyPath).Ready;
if (online) {
string nonce = Guid.NewGuid().ToString("N"), boot = Guid.NewGuid().ToString("N");
string request = Protocol.Sign(Protocol.Map("deviceId", config.DeviceId, "bootId", boot, "nonce", nonce, "at", clock.UnixSeconds, "ready", false, "ack", null), config.Secret);
if (Protocol.VerifyResponse(transport.Post(request), config.Secret, nonce, boot, clock.UnixSeconds) != null) throw new ProtocolException("Server delivered command to a not-ready check");
}
return "device=" + config.DeviceId + "; transport=" + config.Transport + "; secret=DPAPI-valid; maintenance=" + (unlocked ? "unlocked" : "locked") + "; check-ready=false; shutdown=disabled; network=" + (online ? "signed-heartbeat-verified" : "not-used");
}
}
}
+84
View File
@@ -0,0 +1,84 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.ServiceProcess;
using System.Threading;
namespace HomeVisionPower {
internal sealed class PowerService : ServiceBase {
public const string Name = "HomeVisionPower";
public static readonly string Root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Name);
public static readonly string ConfigPath = Path.Combine(Root, "config.json");
public static readonly string LockPath = Path.Combine(Root, "maintenance.lock");
readonly ManualResetEvent stopping = new ManualResetEvent(false);
Thread worker;
public PowerService() { ServiceName = Name; CanStop = true; CanShutdown = true; AutoLog = false; }
protected override void OnStart(string[] args) {
// A virtual service identity prevents an accidental LocalSystem deployment.
var expected = (SecurityIdentifier)new NTAccount("NT SERVICE", Name).Translate(typeof(SecurityIdentifier));
using (var identity = WindowsIdentity.GetCurrent()) {
if (identity.User != expected) throw new InvalidOperationException("Run under the dedicated virtual service account");
}
var config = AgentConfig.Load(ConfigPath);
stopping.Reset();
worker = new Thread(delegate() { RunWorker(config); }); worker.IsBackground = true; worker.Name = Name;
worker.Start();
}
void RunWorker(AgentConfig config) {
try {
using (var journal = new FileJournal(Path.Combine(Root, "state", "consumed.ids"))) {
var engine = new AgentEngine(config.DeviceId, config.Secret, Guid.NewGuid().ToString("N"), journal, new MaintenanceSafety(LockPath), new SystemClock(), new FixedTransport(config.Transport), new WindowsShutdown(new WindowsShutdownApi()), delegate { return stopping.WaitOne(0); });
while (!stopping.WaitOne(0)) {
var elapsed = Stopwatch.StartNew();
try { string outcome = engine.Poll(); if (outcome != "idle") Log(outcome); }
catch (Exception ex) { Log("poll_failed:" + ex.GetType().Name); }
// Ten seconds between poll starts, with no concurrent network operations.
int wait = Math.Max(0, 10000 - (int)Math.Min(elapsed.ElapsedMilliseconds, 10000));
if (stopping.WaitOne(wait)) break;
}
}
} catch (Exception ex) { Log("agent_stopped:" + ex.GetType().Name); }
finally { Array.Clear(config.Secret, 0, config.Secret.Length); }
}
static void Log(string message) {
// No requests, responses, signatures or secrets are logged. Keep log bounded.
try {
string path = Path.Combine(Root, "state", "agent.log");
if (File.Exists(path) && new FileInfo(path).Length > 65536) File.WriteAllText(path, "");
File.AppendAllText(path, DateTime.UtcNow.ToString("o") + " " + message + Environment.NewLine);
} catch (Exception) {}
}
protected override void OnStop() { stopping.Set(); if (worker != null) worker.Join(20000); }
protected override void OnShutdown() { OnStop(); }
}
internal static class Program {
static int Main(string[] args) {
try {
if (args.Length == 1 && args[0] == "--self-test") return SelfTests.Run();
if (args.Length == 1 && args[0] == "--service") {
if (Environment.UserInteractive) throw new InvalidOperationException("Service mode requires the Windows Service Control Manager");
ServiceBase.Run(new PowerService()); return 0;
}
if ((args.Length == 1 || args.Length == 3) && (args[0] == "--check" || args[0] == "--check-online")) {
string path = PowerService.ConfigPath;
if (args.Length == 3) { if (args[1] != "--config") return 2; path = Path.GetFullPath(args[2]); }
AgentConfig config = AgentConfig.Load(path);
try { Console.WriteLine(AgentCheck.Run(config, Path.Combine(Path.GetDirectoryName(path), "maintenance.lock"), args[0] == "--check-online", new FixedTransport(config.Transport), new SystemClock())); }
finally { Array.Clear(config.Secret, 0, config.Secret.Length); }
return 0;
}
if ((args.Length == 3 || args.Length == 4) && args[0] == "--write-config") {
byte[] secret = Convert.FromBase64String(Console.ReadLine() ?? "");
try { AgentConfig.WriteProtected(Path.GetFullPath(args[2]), args[1], secret, args.Length == 4 ? args[3] : "https"); }
finally { Array.Clear(secret, 0, secret.Length); }
Console.WriteLine("DPAPI-protected configuration created."); return 0;
}
Console.WriteLine("HomeVisionPower: --self-test | --check [--config PATH] | --check-online [--config PATH]");
Console.WriteLine("Check modes cannot shut down. Service installation is explicit via install.ps1.");
return 2;
} catch (Exception ex) { Console.Error.WriteLine("HomeVisionPower failed: " + ex.GetType().Name); return 1; }
}
}
}
+152
View File
@@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
namespace HomeVisionPower {
internal static class SelfTests {
static readonly byte[] Key = Encoding.ASCII.GetBytes("0123456789abcdef0123456789abcdef");
const string Boot = "11111111111111111111111111111111";
const string Nonce = "22222222222222222222222222222222";
const string Id = "33333333333333333333333333333333";
const long Now = 1800000000;
static int passed, failed;
static JavaScriptSerializer Json { get { return new JavaScriptSerializer(); } }
static void Assert(bool ok, string message) { if (!ok) throw new Exception(message); }
static string ReadJournal(string path) { using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(file)) return reader.ReadToEnd(); }
static void Reject(Action action) { bool rejected = false; try { action(); } catch (ProtocolException) { rejected = true; } Assert(rejected, "Unsafe response was accepted"); }
static void Test(string name, Action action) { try { action(); passed++; Console.WriteLine("PASS " + name); } catch (Exception ex) { failed++; Console.WriteLine("FAIL " + name + ": " + ex.Message); } }
static Dictionary<string, object> Map(params object[] pairs) { var m = new Dictionary<string, object>(); for (int i = 0; i < pairs.Length; i += 2) m[(string)pairs[i]] = pairs[i+1]; return m; }
static Dictionary<string, object> Command() { return Map("id", Id, "op", 2, "bootId", Boot, "expires", Now + 30); }
// Independent server fixture: production signing/decoding functions are not used here.
static string Envelope(object body) {
string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(Json.Serialize(body)));
byte[] digest; using (var h = new HMACSHA256(Key)) digest = h.ComputeHash(Encoding.ASCII.GetBytes(payload));
return Json.Serialize(Map("payload", payload, "signature", BitConverter.ToString(digest).Replace("-", "").ToLowerInvariant()));
}
static string Reply(object command, string nonce, long at) { return Envelope(Map("nonce", nonce, "at", at, "command", command)); }
static Dictionary<string, object> DecodeRequest(string envelope) {
var outer = Json.Deserialize<Dictionary<string, object>>(envelope);
string payload = (string)outer["payload"];
byte[] digest; using (var h = new HMACSHA256(Key)) digest = h.ComputeHash(Encoding.ASCII.GetBytes(payload));
Assert((string)outer["signature"] == BitConverter.ToString(digest).Replace("-", "").ToLowerInvariant(), "Outbound HMAC mismatch");
return Json.Deserialize<Dictionary<string, object>>(Encoding.UTF8.GetString(Convert.FromBase64String(payload)));
}
sealed class Time : IClock { public long Value = Now; public long UnixSeconds { get { return Value; } } }
sealed class Stopper : IShutdown { public int Calls; public void ShutdownGracefully() { Calls++; } }
sealed class Wire : ITransport { public Func<string, string> Handler; public int Calls; public string Post(string body) { Calls++; return Handler(body); } }
sealed class BrokenJournal : IJournal { public bool Ready { get { return true; } } public bool TryConsume(string id) { throw new IOException("disk failure"); } }
sealed class NativeSpy : IWindowsShutdownApi {
public bool Enabled, Disabled, Initiated, Force, Reboot;
public uint Timeout;
public void EnablePrivilege() { Enabled = true; }
public void DisablePrivilege() { Disabled = true; }
public void Initiate(uint timeout, bool force, bool reboot) { Assert(Enabled, "Shutdown privilege not enabled before call"); Initiated = true; Timeout = timeout; Force = force; Reboot = reboot; }
}
sealed class Case : IDisposable {
public string Dir, JournalPath, LockPath;
public FileJournal Journal;
public Time Clock = new Time();
public Stopper Shutdown = new Stopper();
public Wire Transport = new Wire();
public bool Stopped;
public AgentEngine Engine;
public List<Dictionary<string, object>> Requests = new List<Dictionary<string, object>>();
public Func<Dictionary<string, object>, string> AckReply;
public Action OnAck;
public Case() {
Dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "self-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Dir); JournalPath = Path.Combine(Dir, "consumed.ids"); LockPath = Path.Combine(Dir, "maintenance.lock");
Journal = new FileJournal(JournalPath);
Transport.Handler = delegate(string body) {
var r = DecodeRequest(body); Requests.Add(r);
Assert((string)r["deviceId"] == "p15-test", "Device binding missing");
Assert((string)r["bootId"] == Boot, "Boot binding missing");
Assert(Convert.ToInt64(r["at"]) == Clock.Value, "Request timestamp missing");
if (r["ack"] == null) return Reply(Command(), (string)r["nonce"], Clock.Value);
Assert(ReadJournal(JournalPath).Contains(Id), "ACK sent before durable journal");
Assert(Shutdown.Calls == 0, "Shutdown before ACK");
if (OnAck != null) OnAck();
return AckReply != null ? AckReply(r) : Reply(null, (string)r["nonce"], Clock.Value);
};
Engine = NewEngine(Journal);
}
public AgentEngine NewEngine(IJournal journal) { return new AgentEngine("p15-test", Key, Boot, journal, new MaintenanceSafety(LockPath), Clock, Transport, Shutdown, delegate { return Stopped; }); }
public void Dispose() { Journal.Dispose(); Directory.Delete(Dir, true); }
}
public static int Run() {
passed = failed = 0;
Test("signed command succeeds", delegate { var c = Protocol.VerifyResponse(Reply(Command(), Nonce, Now), Key, Nonce, Boot, Now); Assert(c.Id == Id, "Command missing"); });
Test("tampered signature fails closed", delegate { var m = Json.Deserialize<Dictionary<string, object>>(Reply(Command(), Nonce, Now)); m["signature"] = new string('0', 64); Reject(delegate { Protocol.VerifyResponse(Json.Serialize(m), Key, Nonce, Boot, Now); }); });
Test("nonce binding prevents response replay", delegate { Reject(delegate { Protocol.VerifyResponse(Reply(Command(), Nonce, Now), Key, Boot, Boot, Now); }); });
Test("boot binding prevents process restart replay", delegate { var c = Command(); c["bootId"] = Nonce; Reject(delegate { Protocol.VerifyResponse(Reply(c, Nonce, Now), Key, Nonce, Boot, Now); }); });
Test("timestamps reject stale and future response", delegate { foreach (long at in new long[] { Now - 61, Now + 61, Int64.MaxValue, Int64.MinValue }) Reject(delegate { Protocol.VerifyResponse(Reply(null, Nonce, at), Key, Nonce, Boot, Now); }); });
Test("expiry exact boundary is expired", delegate { var c = Command(); c["expires"] = Now; Reject(delegate { Protocol.VerifyResponse(Reply(c, Nonce, Now), Key, Nonce, Boot, Now); }); });
Test("only numeric shutdown OP2 accepted", delegate { foreach (object op in new object[] { 1, 0, 3, "2", 2.1, true }) { var c = Command(); c["op"] = op; Reject(delegate { Protocol.VerifyResponse(Reply(c, Nonce, Now), Key, Nonce, Boot, Now); }); } });
Test("arbitrary command arguments rejected", delegate { var c = Command(); c["args"] = "/f"; Reject(delegate { Protocol.VerifyResponse(Reply(c, Nonce, Now), Key, Nonce, Boot, Now); }); });
Test("invalid command ID rejected", delegate { var c = Command(); c["id"] = "cmd.exe"; Reject(delegate { Protocol.VerifyResponse(Reply(c, Nonce, Now), Key, Nonce, Boot, Now); }); });
Test("oversize and malformed envelopes rejected", delegate { foreach (string data in new string[] { new string('a', 16385), "{}", "null", "[]", "{\"payload\":\"?\",\"signature\":\"x\"}" }) Reject(delegate { Protocol.VerifyResponse(data, Key, Nonce, Boot, Now); }); });
Test("journal persists before ACK and shutdown", delegate { using (var t = new Case()) { t.Engine.Poll(); Assert(t.Shutdown.Calls == 1, "Graceful shutdown missing"); Assert(t.Requests.Count == 2, "ACK missing"); var ack = (Dictionary<string, object>)t.Requests[1]["ack"]; Assert((string)ack["status"] == "scheduled" && (string)ack["id"] == Id, "Scheduled ACK missing"); Assert((string)t.Requests[0]["nonce"] != (string)t.Requests[1]["nonce"], "Nonce reused"); } });
Test("journal stops same process duplicate", delegate { using (var t = new Case()) { t.Engine.Poll(); t.Engine.Poll(); Assert(t.Shutdown.Calls == 1, "Duplicate shutdown"); } });
Test("journal stops restart duplicate", delegate { using (var t = new Case()) { Assert(t.Journal.TryConsume(Id), "Initial consume failed"); t.Journal.Dispose(); t.Journal = new FileJournal(t.JournalPath); t.Engine = t.NewEngine(t.Journal); t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Restart replayed command"); } });
Test("failed ACK permanently consumes command", delegate { using (var t = new Case()) { t.AckReply = delegate { throw new IOException("network"); }; t.Engine.Poll(); t.AckReply = null; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Failed ACK later executed"); Assert(ReadJournal(t.JournalPath).Contains(Id), "Consumed record lost"); } });
Test("unsigned ACK does not authorize shutdown", delegate { using (var t = new Case()) { t.AckReply = delegate { return "{}"; }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Unverified ACK allowed shutdown"); } });
Test("ACK nonce mismatch does not authorize shutdown", delegate { using (var t = new Case()) { t.AckReply = delegate { return Reply(null, Nonce, Now); }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Wrong ACK nonce allowed shutdown"); } });
Test("ACK carrying another command is rejected", delegate { using (var t = new Case()) { t.AckReply = delegate(Dictionary<string, object> r) { return Reply(Command(), (string)r["nonce"], Now); }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "ACK piggyback command accepted"); } });
Test("maintenance lock advertises not ready and blocks", delegate { using (var t = new Case()) { File.WriteAllText(t.LockPath, "locked"); t.Engine.Poll(); Assert(!(bool)t.Requests[0]["ready"], "Lock ignored in ready flag"); Assert(t.Shutdown.Calls == 0, "Lock ignored on execution"); Assert((string)((Dictionary<string, object>)t.Requests[1]["ack"])["status"] == "blocked", "Blocked ACK missing"); } });
Test("new maintenance lock after ACK blocks shutdown", delegate { using (var t = new Case()) { t.OnAck = delegate { File.WriteAllText(t.LockPath, "locked"); }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Race ignored maintenance lock"); } });
Test("expiry during ACK blocks shutdown", delegate { using (var t = new Case()) { t.OnAck = delegate { t.Clock.Value = Now + 30; }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Expired during ACK executed"); } });
Test("service stop during ACK blocks shutdown", delegate { using (var t = new Case()) { t.OnAck = delegate { t.Stopped = true; }; t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Service stop ignored"); } });
Test("journal failure cannot ACK scheduled or shutdown", delegate { using (var t = new Case()) { t.Engine = t.NewEngine(new BrokenJournal()); t.Engine.Poll(); Assert(t.Shutdown.Calls == 0, "Persistence failure executed"); foreach (var r in t.Requests) if (r["ack"] != null) Assert((string)((Dictionary<string, object>)r["ack"])["status"] != "scheduled", "Scheduled without durable consume"); } });
Test("corrupt journal fails closed", delegate { using (var t = new Case()) { t.Journal.Dispose(); File.WriteAllText(t.JournalPath, Id.Substring(0, 12)); bool rejected = false; try { using (var j = new FileJournal(t.JournalPath)) {} } catch (IOException) { rejected = true; } Assert(rejected, "Partial journal accepted"); } });
Test("journal capacity fails closed without eviction", delegate { using (var t = new Case()) { t.Journal.Dispose(); var lines = new StringBuilder(); for (int i = 0; i < FileJournal.Capacity; i++) lines.Append(i.ToString("x32")).Append('\n'); File.WriteAllText(t.JournalPath, lines.ToString(), new UTF8Encoding(false)); t.Journal = new FileJournal(t.JournalPath); Assert(!t.Journal.Ready, "Full journal ready"); Assert(!t.Journal.TryConsume(Id), "Full journal accepted command"); Assert(!t.Journal.TryConsume(new string('0', 32)), "Old ID evicted"); } });
Test("Windows adapter never forces apps or reboots", delegate { var spy = new NativeSpy(); new WindowsShutdown(spy).ShutdownGracefully(); Assert(spy.Initiated && !spy.Force && !spy.Reboot && spy.Timeout == 0 && spy.Disabled, "Unsafe Windows shutdown flags or privilege not released"); });
Test("check mode is read-only and non-network by default", delegate { using (var t = new Case()) { string config = Path.Combine(t.Dir, "config.json"); AgentConfig.WriteProtected(config, "p15-test", Key); File.WriteAllText(t.LockPath, "locked"); var loaded = AgentConfig.Load(config); Assert(loaded.DeviceId == "p15-test" && Convert.ToBase64String(loaded.Secret) == Convert.ToBase64String(Key), "DPAPI configuration roundtrip failed"); Assert(!File.ReadAllText(config).Contains(Convert.ToBase64String(Key)), "Plain secret written to disk"); var report = AgentCheck.Run(loaded, t.LockPath, false, t.Transport, t.Clock); Assert(report.Contains("maintenance=locked") && t.Transport.Calls == 0 && t.Shutdown.Calls == 0, "Offline check had side effects"); } });
Test("online check always advertises not ready", delegate { using (var t = new Case()) { bool ready = true; t.Transport.Handler = delegate(string body) { var r = DecodeRequest(body); ready = (bool)r["ready"]; Assert(r["ack"] == null, "Check sent command acknowledgement"); return Reply(null, (string)r["nonce"], Now); }; var config = new AgentConfig { DeviceId = "p15-test", Secret = Key }; AgentCheck.Run(config, t.LockPath, true, t.Transport, t.Clock); Assert(!ready && t.Shutdown.Calls == 0 && ReadJournal(t.JournalPath) == "", "Online check changed power state or journal"); } });
Test("online check rejects any delivered command without executing", delegate { using (var t = new Case()) { t.Transport.Handler = delegate(string body) { var r = DecodeRequest(body); var c = Command(); c["bootId"] = (string)r["bootId"]; return Reply(c, (string)r["nonce"], Now); }; var config = new AgentConfig { DeviceId = "p15-test", Secret = Key }; Reject(delegate { AgentCheck.Run(config, t.LockPath, true, t.Transport, t.Clock); }); Assert(t.Shutdown.Calls == 0 && ReadJournal(t.JournalPath) == "", "Check executed or consumed command"); } });
Test("invalid protected config never falls back to raw secret", delegate { using (var t = new Case()) { string config = Path.Combine(t.Dir, "config.json"); File.WriteAllText(config, Json.Serialize(Map("deviceId", "p15-test", "protectedSecret", Convert.ToBase64String(Key)))); bool rejected = false; try { AgentConfig.Load(config); } catch (Exception) { rejected = true; } Assert(rejected, "Invalid DPAPI blob accepted"); } });
Test("missing maintenance directory fails closed", delegate { using (var t = new Case()) Assert(!new MaintenanceSafety(Path.Combine(t.Dir, "missing", "maintenance.lock")).Ready, "Missing safety root ready"); });
Test("transport selection uses fixed HTTPS and Tailnet endpoints without redirects", delegate {
var https = new FixedTransport("https").CreateRequest(10);
var tail = new FixedTransport("tailscale").CreateRequest(10);
Assert(https.RequestUri.AbsoluteUri == "https://home.ucvl.cn/api/device-power/agent", "HTTPS endpoint changed");
Assert(tail.RequestUri.AbsoluteUri == "http://100.115.230.91:8790/api/device-power/agent", "Tailnet endpoint changed");
Assert(https.Method == "POST" && tail.Method == "POST" && !https.AllowAutoRedirect && !tail.AllowAutoRedirect && https.Proxy == null && tail.Proxy == null && !https.UseDefaultCredentials && !tail.UseDefaultCredentials, "Transport allowed redirect, credentials or proxy");
});
Test("unknown or arbitrary transport fails closed", delegate {
foreach (string mode in new string[] { null, "", "HTTPS", "http", "tailscale ", "http://127.0.0.1/", "https://example.com/" }) Reject(delegate { new FixedTransport(mode); });
});
Test("new protected configuration persists explicit Tailnet choice", delegate { using (var t = new Case()) {
string path = Path.Combine(t.Dir, "tail.json"); AgentConfig.WriteProtected(path, "p15-test", Key, "tailscale"); var config = AgentConfig.Load(path);
Assert(config.Transport == "tailscale" && Convert.ToBase64String(config.Secret) == Convert.ToBase64String(Key), "Tailnet choice lost");
Assert(!File.ReadAllText(path).Contains(Convert.ToBase64String(Key)), "Plain secret written");
} });
Test("HTTPS remains default for newly written configuration", delegate { using (var t = new Case()) {
string path = Path.Combine(t.Dir, "https.json"); AgentConfig.WriteProtected(path, "p15-test", Key); var config = AgentConfig.Load(path);
Assert(config.Transport == "https", "Default transport silently downgraded");
} });
Test("legacy configuration remains HTTPS only", delegate { using (var t = new Case()) {
string path = Path.Combine(t.Dir, "legacy.json"); byte[] blob = ProtectedData.Protect(Key, Encoding.UTF8.GetBytes("HomeVisionPower/config/v1"), DataProtectionScope.LocalMachine);
File.WriteAllText(path, Json.Serialize(Map("deviceId", "p15-test", "protectedSecret", Convert.ToBase64String(blob))));
var config = AgentConfig.Load(path); Assert(config.Transport == "https" && Convert.ToBase64String(config.Secret) == Convert.ToBase64String(Key), "Legacy config changed transport");
} });
Test("transport selector is bound to protected secret", delegate { using (var t = new Case()) {
string path = Path.Combine(t.Dir, "tampered.json"); AgentConfig.WriteProtected(path, "p15-test", Key, "https");
var json = Json.Deserialize<Dictionary<string, object>>(File.ReadAllText(path)); json["transport"] = "tailscale"; File.WriteAllText(path, Json.Serialize(json));
bool rejected = false; try { AgentConfig.Load(path); } catch (CryptographicException) { rejected = true; } Assert(rejected, "Changing config selector bypassed DPAPI binding");
} });
Test("invalid transport is rejected before writing configuration", delegate { using (var t = new Case()) {
string path = Path.Combine(t.Dir, "invalid.json"); Reject(delegate { AgentConfig.WriteProtected(path, "p15-test", Key, "http://example.com"); }); Assert(!File.Exists(path), "Invalid choice wrote config");
} });
Test("Tailnet online check has no action and never transmits its secret", delegate { using (var t = new Case()) {
t.Transport.Handler = delegate(string body) { var r = DecodeRequest(body); Assert(!(bool)r["ready"] && r["ack"] == null, "Check enabled action"); Assert(r.Count == 6 && !r.ContainsKey("secret") && !r.ContainsKey("transport"), "Sensitive/local configuration sent on wire"); return Reply(null, (string)r["nonce"], Now); };
var config = new AgentConfig { DeviceId = "p15-test", Secret = Key, Transport = "tailscale" }; string report = AgentCheck.Run(config, t.LockPath, true, t.Transport, t.Clock);
Assert(report.Contains("transport=tailscale") && t.Shutdown.Calls == 0 && ReadJournal(t.JournalPath) == "", "Tailnet check changed power/journal or concealed transport");
} });
Console.WriteLine("Self-test result: " + passed + " passed, " + failed + " failed. Fake shutdown only; no network/service changes.");
return failed == 0 ? 0 : 1;
}
}
}
+23
View File
@@ -0,0 +1,23 @@
[CmdletBinding()]
param([switch]$Plan)
$ErrorActionPreference = 'Stop'
$serviceName = 'HomeVisionPower'
$dataRoot = Join-Path $env:ProgramData $serviceName
$scExe = Join-Path $env:WINDIR 'System32\sc.exe'
if ($Plan) {
Write-Output 'Stop/disable HomeVisionPower, retain maintenance.lock, remove only its SeShutdownPrivilege assignment, delete service registration; retain binary, DPAPI config and journal.'
return
}
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run the explicit uninstaller in an elevated PowerShell.' }
$service = Get-Service -Name $serviceName -ErrorAction Stop
Set-Service -Name $serviceName -StartupType Disabled
Stop-Service -Name $serviceName -ErrorAction Stop
$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, [TimeSpan]::FromSeconds(30))
if (Test-Path -LiteralPath $dataRoot -PathType Container) { [IO.File]::WriteAllText((Join-Path $dataRoot 'maintenance.lock'), 'Service uninstalled; safety lock retained.') }
$serviceSid = ([Security.Principal.NTAccount]"NT SERVICE\$serviceName").Translate([Security.Principal.SecurityIdentifier])
Add-Type -Path (Join-Path $PSScriptRoot 'ServiceRights.cs')
[HomeVisionServiceRights]::SetShutdownRight($serviceSid, $false)
& $scExe delete $serviceName
if ($LASTEXITCODE -ne 0) { throw 'Service registration deletion failed.' }
Write-Output 'Service removed. Binary, protected configuration and consumed-command journal were retained for recovery/audit.'