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 Map(params object[] pairs) { var m = new Dictionary(); for (int i = 0; i < pairs.Length; i += 2) m[(string)pairs[i]] = pairs[i+1]; return m; } static Dictionary 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 DecodeRequest(string envelope) { var outer = Json.Deserialize>(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>(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 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> Requests = new List>(); public Func, 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>(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)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 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)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)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>(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; } } }